home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / perl5 / DateTime.pm < prev    next >
Encoding:
Perl POD Document  |  2010-07-30  |  112.9 KB  |  4,060 lines

  1. package DateTime;
  2. BEGIN {
  3.   $DateTime::VERSION = '0.61';
  4. }
  5.  
  6. use 5.006;
  7.  
  8. use strict;
  9. use warnings;
  10.  
  11. use Carp;
  12. use DateTime::Helpers;
  13.  
  14. BEGIN {
  15.     my $loaded = 0;
  16.     unless ( $ENV{PERL_DATETIME_PP} ) {
  17.         local $@;
  18.         eval {
  19.             require XSLoader;
  20.             XSLoader::load( 'DateTime', $DateTime::VERSION );
  21.  
  22.             $DateTime::IsPurePerl = 0;
  23.         };
  24.  
  25.         die $@ if $@ && $@ !~ /object version|loadable object/;
  26.  
  27.         $loaded = 1 unless $@;
  28.     }
  29.  
  30.     if ($loaded) {
  31.         require DateTimePPExtra
  32.             unless defined &DateTime::_normalize_tai_seconds;
  33.     }
  34.     else {
  35.         require DateTimePP;
  36.     }
  37. }
  38.  
  39. use DateTime::Duration;
  40. use DateTime::Locale 0.40;
  41. use DateTime::TimeZone 0.59;
  42. use Time::Local qw( timegm_nocheck );
  43. use Params::Validate
  44.     qw( validate validate_pos UNDEF SCALAR BOOLEAN HASHREF OBJECT );
  45.  
  46. # for some reason, overloading doesn't work unless fallback is listed
  47. # early.
  48. #
  49. # 3rd parameter ( $_[2] ) means the parameters are 'reversed'.
  50. # see: "Calling conventions for binary operations" in overload docs.
  51. #
  52. use overload (
  53.     'fallback' => 1,
  54.     '<=>'      => '_compare_overload',
  55.     'cmp'      => '_string_compare_overload',
  56.     '""'       => '_stringify',
  57.     '-'        => '_subtract_overload',
  58.     '+'        => '_add_overload',
  59.     'eq'       => '_string_equals_overload',
  60.     'ne'       => '_string_not_equals_overload',
  61. );
  62.  
  63. # Have to load this after overloading is defined, after BEGIN blocks
  64. # or else weird crashes ensue
  65. require DateTime::Infinite;
  66.  
  67. use constant MAX_NANOSECONDS => 1_000_000_000;    # 1E9 = almost 32 bits
  68.  
  69. use constant INFINITY     => ( 9**9**9 );
  70. use constant NEG_INFINITY => -1 * ( 9**9**9 );
  71. use constant NAN          => INFINITY - INFINITY;
  72.  
  73. use constant SECONDS_PER_DAY => 86400;
  74.  
  75. use constant duration_class => 'DateTime::Duration';
  76.  
  77. my ( @MonthLengths, @LeapYearMonthLengths );
  78.  
  79. BEGIN {
  80.     @MonthLengths = ( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 );
  81.  
  82.     @LeapYearMonthLengths = @MonthLengths;
  83.     $LeapYearMonthLengths[1]++;
  84. }
  85.  
  86. {
  87.  
  88.     # I'd rather use Class::Data::Inheritable for this, but there's no
  89.     # way to add the module-loading behavior to an accessor it
  90.     # creates, despite what its docs say!
  91.     my $DefaultLocale;
  92.  
  93.     sub DefaultLocale {
  94.         my $class = shift;
  95.  
  96.         if (@_) {
  97.             my $lang = shift;
  98.  
  99.             DateTime::Locale->load($lang);
  100.  
  101.             $DefaultLocale = $lang;
  102.         }
  103.  
  104.         return $DefaultLocale;
  105.     }
  106.  
  107.     # backwards compat
  108.     *DefaultLanguage = \&DefaultLocale;
  109. }
  110. __PACKAGE__->DefaultLocale('en_US');
  111.  
  112. my $BasicValidate = {
  113.     year => {
  114.         type      => SCALAR,
  115.         callbacks => {
  116.             'is an integer' => sub { $_[0] =~ /^-?\d+$/ }
  117.         },
  118.     },
  119.     month => {
  120.         type      => SCALAR,
  121.         default   => 1,
  122.         callbacks => {
  123.             'an integer between 1 and 12' =>
  124.                 sub { $_[0] =~ /^\d+$/ && $_[0] >= 1 && $_[0] <= 12 }
  125.         },
  126.     },
  127.     day => {
  128.         type      => SCALAR,
  129.         default   => 1,
  130.         callbacks => {
  131.             'an integer which is a possible valid day of month' =>
  132.                 sub { $_[0] =~ /^\d+$/ && $_[0] >= 1 && $_[0] <= 31 }
  133.         },
  134.     },
  135.     hour => {
  136.         type      => SCALAR,
  137.         default   => 0,
  138.         callbacks => {
  139.             'an integer between 0 and 23' =>
  140.                 sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 23 },
  141.         },
  142.     },
  143.     minute => {
  144.         type      => SCALAR,
  145.         default   => 0,
  146.         callbacks => {
  147.             'an integer between 0 and 59' =>
  148.                 sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 59 },
  149.         },
  150.     },
  151.     second => {
  152.         type      => SCALAR,
  153.         default   => 0,
  154.         callbacks => {
  155.             'an integer between 0 and 61' =>
  156.                 sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 && $_[0] <= 61 },
  157.         },
  158.     },
  159.     nanosecond => {
  160.         type      => SCALAR,
  161.         default   => 0,
  162.         callbacks => {
  163.             'a positive integer' => sub { $_[0] =~ /^\d+$/ && $_[0] >= 0 },
  164.         }
  165.     },
  166.     locale => {
  167.         type    => SCALAR | OBJECT,
  168.         default => undef
  169.     },
  170.     language => {
  171.         type     => SCALAR | OBJECT,
  172.         optional => 1
  173.     },
  174.     formatter => {
  175.         type      => UNDEF | SCALAR | OBJECT,
  176.         optional  => 1,
  177.         callbacks => {
  178.             'can format_datetime' =>
  179.                 sub { defined $_[0] ? $_[0]->can('format_datetime') : 1 },
  180.         },
  181.     },
  182. };
  183.  
  184. my $NewValidate = {
  185.     %$BasicValidate,
  186.     time_zone => {
  187.         type    => SCALAR | OBJECT,
  188.         default => 'floating'
  189.     },
  190. };
  191.  
  192. sub new {
  193.     my $class = shift;
  194.     my %p = validate( @_, $NewValidate );
  195.  
  196.     Carp::croak(
  197.         "Invalid day of month (day = $p{day} - month = $p{month} - year = $p{year})\n"
  198.     ) if $p{day} > $class->_month_length( $p{year}, $p{month} );
  199.  
  200.     my $self = bless {}, $class;
  201.  
  202.     $p{locale} = delete $p{language} if exists $p{language};
  203.     $p{locale} = $class->DefaultLocale unless defined $p{locale};
  204.  
  205.     if ( ref $p{locale} ) {
  206.         $self->{locale} = $p{locale};
  207.     }
  208.     else {
  209.         $self->{locale} = DateTime::Locale->load( $p{locale} );
  210.     }
  211.  
  212.     $self->{tz} = (
  213.         ref $p{time_zone}
  214.         ? $p{time_zone}
  215.         : DateTime::TimeZone->new( name => $p{time_zone} )
  216.     );
  217.  
  218.     $self->{local_rd_days} = $class->_ymd2rd( @p{qw( year month day )} );
  219.  
  220.     $self->{local_rd_secs}
  221.         = $class->_time_as_seconds( @p{qw( hour minute second )} );
  222.  
  223.     $self->{offset_modifier} = 0;
  224.  
  225.     $self->{rd_nanosecs} = $p{nanosecond};
  226.     $self->{formatter}   = $p{formatter};
  227.  
  228.     $self->_normalize_nanoseconds( $self->{local_rd_secs},
  229.         $self->{rd_nanosecs} );
  230.  
  231.     # Set this explicitly since it can't be calculated accurately
  232.     # without knowing our time zone offset, and it's possible that the
  233.     # offset can't be calculated without having at least a rough guess
  234.     # of the datetime's year.  This year need not be correct, as long
  235.     # as its equal or greater to the correct number, so we fudge by
  236.     # adding one to the local year given to the constructor.
  237.     $self->{utc_year} = $p{year} + 1;
  238.  
  239.     $self->_calc_utc_rd;
  240.  
  241.     $self->_handle_offset_modifier( $p{second} );
  242.  
  243.     $self->_calc_local_rd;
  244.  
  245.     if ( $p{second} > 59 ) {
  246.         if (
  247.             $self->{tz}->is_floating
  248.             ||
  249.  
  250.             # If true, this means that the actual calculated leap
  251.             # second does not occur in the second given to new()
  252.             ( $self->{utc_rd_secs} - 86399 < $p{second} - 59 )
  253.             ) {
  254.             Carp::croak("Invalid second value ($p{second})\n");
  255.         }
  256.     }
  257.  
  258.     return $self;
  259. }
  260.  
  261. # This method exists for the benefit of internal methods which create
  262. # a new object based on the current object, like set() and truncate().
  263. sub _new_from_self {
  264.     my $self = shift;
  265.  
  266.     my %old = map { $_ => $self->$_() }
  267.         qw( year month day hour minute second nanosecond
  268.         locale time_zone );
  269.     $old{formatter} = $self->formatter()
  270.         if defined $self->formatter();
  271.  
  272.     return ( ref $self )->new( %old, @_ );
  273. }
  274.  
  275. sub _handle_offset_modifier {
  276.     my $self = shift;
  277.  
  278.     $self->{offset_modifier} = 0;
  279.  
  280.     return if $self->{tz}->is_floating;
  281.  
  282.     my $second       = shift;
  283.     my $utc_is_valid = shift;
  284.  
  285.     my $utc_rd_days = $self->{utc_rd_days};
  286.  
  287.     my $offset
  288.         = $utc_is_valid ? $self->offset : $self->_offset_for_local_datetime;
  289.  
  290.     if (   $offset >= 0
  291.         && $self->{local_rd_secs} >= $offset ) {
  292.         if ( $second < 60 && $offset > 0 ) {
  293.             $self->{offset_modifier}
  294.                 = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
  295.  
  296.             $self->{local_rd_secs} += $self->{offset_modifier};
  297.         }
  298.         elsif (
  299.             $second == 60
  300.             && (
  301.                 ( $self->{local_rd_secs} == $offset && $offset > 0 )
  302.                 || (   $offset == 0
  303.                     && $self->{local_rd_secs} > 86399 )
  304.             )
  305.             ) {
  306.             my $mod
  307.                 = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
  308.  
  309.             unless ( $mod == 0 ) {
  310.                 $self->{utc_rd_secs} -= $mod;
  311.  
  312.                 $self->_normalize_seconds;
  313.             }
  314.         }
  315.     }
  316.     elsif ($offset < 0
  317.         && $self->{local_rd_secs} >= SECONDS_PER_DAY + $offset ) {
  318.         if ( $second < 60 ) {
  319.             $self->{offset_modifier}
  320.                 = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
  321.  
  322.             $self->{local_rd_secs} += $self->{offset_modifier};
  323.         }
  324.         elsif ($second == 60
  325.             && $self->{local_rd_secs} == SECONDS_PER_DAY + $offset ) {
  326.             my $mod
  327.                 = $self->_day_length( $utc_rd_days - 1 ) - SECONDS_PER_DAY;
  328.  
  329.             unless ( $mod == 0 ) {
  330.                 $self->{utc_rd_secs} -= $mod;
  331.  
  332.                 $self->_normalize_seconds;
  333.             }
  334.         }
  335.     }
  336. }
  337.  
  338. sub _calc_utc_rd {
  339.     my $self = shift;
  340.  
  341.     delete $self->{utc_c};
  342.  
  343.     if ( $self->{tz}->is_utc || $self->{tz}->is_floating ) {
  344.         $self->{utc_rd_days} = $self->{local_rd_days};
  345.         $self->{utc_rd_secs} = $self->{local_rd_secs};
  346.     }
  347.     else {
  348.         my $offset = $self->_offset_for_local_datetime;
  349.  
  350.         $offset += $self->{offset_modifier};
  351.  
  352.         $self->{utc_rd_days} = $self->{local_rd_days};
  353.         $self->{utc_rd_secs} = $self->{local_rd_secs} - $offset;
  354.     }
  355.  
  356.     # We account for leap seconds in the new() method and nowhere else
  357.     # except date math.
  358.     $self->_normalize_tai_seconds( $self->{utc_rd_days},
  359.         $self->{utc_rd_secs} );
  360. }
  361.  
  362. sub _normalize_seconds {
  363.     my $self = shift;
  364.  
  365.     return if $self->{utc_rd_secs} >= 0 && $self->{utc_rd_secs} <= 86399;
  366.  
  367.     if ( $self->{tz}->is_floating ) {
  368.         $self->_normalize_tai_seconds( $self->{utc_rd_days},
  369.             $self->{utc_rd_secs} );
  370.     }
  371.     else {
  372.         $self->_normalize_leap_seconds( $self->{utc_rd_days},
  373.             $self->{utc_rd_secs} );
  374.     }
  375. }
  376.  
  377. sub _calc_local_rd {
  378.     my $self = shift;
  379.  
  380.     delete $self->{local_c};
  381.  
  382.     # We must short circuit for UTC times or else we could end up with
  383.     # loops between DateTime.pm and DateTime::TimeZone
  384.     if ( $self->{tz}->is_utc || $self->{tz}->is_floating ) {
  385.         $self->{local_rd_days} = $self->{utc_rd_days};
  386.         $self->{local_rd_secs} = $self->{utc_rd_secs};
  387.     }
  388.     else {
  389.         my $offset = $self->offset;
  390.  
  391.         $self->{local_rd_days} = $self->{utc_rd_days};
  392.         $self->{local_rd_secs} = $self->{utc_rd_secs} + $offset;
  393.  
  394.         # intentionally ignore leap seconds here
  395.         $self->_normalize_tai_seconds( $self->{local_rd_days},
  396.             $self->{local_rd_secs} );
  397.  
  398.         $self->{local_rd_secs} += $self->{offset_modifier};
  399.     }
  400.  
  401.     $self->_calc_local_components;
  402. }
  403.  
  404. sub _calc_local_components {
  405.     my $self = shift;
  406.  
  407.     @{ $self->{local_c} }{
  408.         qw( year month day day_of_week
  409.             day_of_year quarter day_of_quarter)
  410.         }
  411.         = $self->_rd2ymd( $self->{local_rd_days}, 1 );
  412.  
  413.     @{ $self->{local_c} }{qw( hour minute second )}
  414.         = $self->_seconds_as_components( $self->{local_rd_secs},
  415.         $self->{utc_rd_secs}, $self->{offset_modifier} );
  416. }
  417.  
  418. sub _calc_utc_components {
  419.     my $self = shift;
  420.  
  421.     die "Cannot get UTC components before UTC RD has been calculated\n"
  422.         unless defined $self->{utc_rd_days};
  423.  
  424.     @{ $self->{utc_c} }{qw( year month day )}
  425.         = $self->_rd2ymd( $self->{utc_rd_days} );
  426.  
  427.     @{ $self->{utc_c} }{qw( hour minute second )}
  428.         = $self->_seconds_as_components( $self->{utc_rd_secs} );
  429. }
  430.  
  431. sub _utc_ymd {
  432.     my $self = shift;
  433.  
  434.     $self->_calc_utc_components unless exists $self->{utc_c}{year};
  435.  
  436.     return @{ $self->{utc_c} }{qw( year month day )};
  437. }
  438.  
  439. sub _utc_hms {
  440.     my $self = shift;
  441.  
  442.     $self->_calc_utc_components unless exists $self->{utc_c}{hour};
  443.  
  444.     return @{ $self->{utc_c} }{qw( hour minute second )};
  445. }
  446.  
  447. {
  448.     my $spec = {
  449.         epoch     => { regex => qr/^-?(?:\d+(?:\.\d*)?|\.\d+)$/ },
  450.         locale    => { type  => SCALAR | OBJECT, optional => 1 },
  451.         language  => { type  => SCALAR | OBJECT, optional => 1 },
  452.         time_zone => { type  => SCALAR | OBJECT, optional => 1 },
  453.         formatter => {
  454.             type     => SCALAR | OBJECT, can => 'format_datetime',
  455.             optional => 1
  456.         },
  457.     };
  458.  
  459.     sub from_epoch {
  460.         my $class = shift;
  461.         my %p = validate( @_, $spec );
  462.  
  463.         my %args;
  464.  
  465.         # Because epoch may come from Time::HiRes
  466.         my $fraction = $p{epoch} - int( $p{epoch} );
  467.         $args{nanosecond} = int( $fraction * MAX_NANOSECONDS )
  468.             if $fraction;
  469.  
  470.         # Note, for very large negative values this may give a
  471.         # blatantly wrong answer.
  472.         @args{qw( second minute hour day month year )}
  473.             = ( gmtime( int delete $p{epoch} ) )[ 0 .. 5 ];
  474.         $args{year} += 1900;
  475.         $args{month}++;
  476.  
  477.         my $self = $class->new( %p, %args, time_zone => 'UTC' );
  478.  
  479.         $self->set_time_zone( $p{time_zone} ) if exists $p{time_zone};
  480.  
  481.         return $self;
  482.     }
  483. }
  484.  
  485. # use scalar time in case someone's loaded Time::Piece
  486. sub now { shift->from_epoch( epoch => ( scalar time ), @_ ) }
  487.  
  488. sub today { shift->now(@_)->truncate( to => 'day' ) }
  489.  
  490. {
  491.     my $spec = {
  492.         object => {
  493.             type => OBJECT,
  494.             can  => 'utc_rd_values',
  495.         },
  496.         locale    => { type => SCALAR | OBJECT, optional => 1 },
  497.         language  => { type => SCALAR | OBJECT, optional => 1 },
  498.         formatter => {
  499.             type     => SCALAR | OBJECT, can => 'format_datetime',
  500.             optional => 1
  501.         },
  502.     };
  503.  
  504.     sub from_object {
  505.         my $class = shift;
  506.         my %p = validate( @_, $spec );
  507.  
  508.         my $object = delete $p{object};
  509.  
  510.         my ( $rd_days, $rd_secs, $rd_nanosecs ) = $object->utc_rd_values;
  511.  
  512.         # A kludge because until all calendars are updated to return all
  513.         # three values, $rd_nanosecs could be undef
  514.         $rd_nanosecs ||= 0;
  515.  
  516.         # This is a big hack to let _seconds_as_components operate naively
  517.         # on the given value.  If the object _is_ on a leap second, we'll
  518.         # add that to the generated seconds value later.
  519.         my $leap_seconds = 0;
  520.         if (   $object->can('time_zone')
  521.             && !$object->time_zone->is_floating
  522.             && $rd_secs > 86399
  523.             && $rd_secs <= $class->_day_length($rd_days) ) {
  524.             $leap_seconds = $rd_secs - 86399;
  525.             $rd_secs -= $leap_seconds;
  526.         }
  527.  
  528.         my %args;
  529.         @args{qw( year month day )} = $class->_rd2ymd($rd_days);
  530.         @args{qw( hour minute second )}
  531.             = $class->_seconds_as_components($rd_secs);
  532.         $args{nanosecond} = $rd_nanosecs;
  533.  
  534.         $args{second} += $leap_seconds;
  535.  
  536.         my $new = $class->new( %p, %args, time_zone => 'UTC' );
  537.  
  538.         if ( $object->can('time_zone') ) {
  539.             $new->set_time_zone( $object->time_zone );
  540.         }
  541.         else {
  542.             $new->set_time_zone('floating');
  543.         }
  544.  
  545.         return $new;
  546.     }
  547. }
  548.  
  549. my $LastDayOfMonthValidate = {%$NewValidate};
  550. foreach ( keys %$LastDayOfMonthValidate ) {
  551.     my %copy = %{ $LastDayOfMonthValidate->{$_} };
  552.  
  553.     delete $copy{default};
  554.     $copy{optional} = 1 unless $_ eq 'year' || $_ eq 'month';
  555.  
  556.     $LastDayOfMonthValidate->{$_} = \%copy;
  557. }
  558.  
  559. sub last_day_of_month {
  560.     my $class = shift;
  561.     my %p = validate( @_, $LastDayOfMonthValidate );
  562.  
  563.     my $day = $class->_month_length( $p{year}, $p{month} );
  564.  
  565.     return $class->new( %p, day => $day );
  566. }
  567.  
  568. sub _month_length {
  569.     return (
  570.           $_[0]->_is_leap_year( $_[1] )
  571.         ? $LeapYearMonthLengths[ $_[2] - 1 ]
  572.         : $MonthLengths[ $_[2] - 1 ]
  573.     );
  574. }
  575.  
  576. my $FromDayOfYearValidate = {%$NewValidate};
  577. foreach ( keys %$FromDayOfYearValidate ) {
  578.     next if $_ eq 'month' || $_ eq 'day';
  579.  
  580.     my %copy = %{ $FromDayOfYearValidate->{$_} };
  581.  
  582.     delete $copy{default};
  583.     $copy{optional} = 1 unless $_ eq 'year' || $_ eq 'month';
  584.  
  585.     $FromDayOfYearValidate->{$_} = \%copy;
  586. }
  587. $FromDayOfYearValidate->{day_of_year} = {
  588.     type      => SCALAR,
  589.     callbacks => {
  590.         'is between 1 and 366' => sub { $_[0] >= 1 && $_[0] <= 366 }
  591.     }
  592. };
  593.  
  594. sub from_day_of_year {
  595.     my $class = shift;
  596.     my %p = validate( @_, $FromDayOfYearValidate );
  597.  
  598.     my $is_leap_year = $class->_is_leap_year( $p{year} );
  599.  
  600.     Carp::croak("$p{year} is not a leap year.\n")
  601.         if $p{day_of_year} == 366 && !$is_leap_year;
  602.  
  603.     my $month = 1;
  604.     my $day   = delete $p{day_of_year};
  605.  
  606.     while ( $month <= 12 && $day > $class->_month_length( $p{year}, $month ) )
  607.     {
  608.         $day -= $class->_month_length( $p{year}, $month );
  609.         $month++;
  610.     }
  611.  
  612.     return DateTime->new(
  613.         %p,
  614.         month => $month,
  615.         day   => $day,
  616.     );
  617. }
  618.  
  619. sub formatter { $_[0]->{formatter} }
  620.  
  621. sub clone { bless { %{ $_[0] } }, ref $_[0] }
  622.  
  623. sub year {
  624.     Carp::carp('year() is a read-only accessor') if @_ > 1;
  625.     return $_[0]->{local_c}{year};
  626. }
  627.  
  628. sub ce_year {
  629.     $_[0]->{local_c}{year} <= 0
  630.         ? $_[0]->{local_c}{year} - 1
  631.         : $_[0]->{local_c}{year};
  632. }
  633.  
  634. sub era_name { $_[0]->{locale}->era_wide->[ $_[0]->_era_index() ] }
  635.  
  636. sub era_abbr { $_[0]->{locale}->era_abbreviated->[ $_[0]->_era_index() ] }
  637.  
  638. # deprecated
  639. *era = \&era_abbr;
  640.  
  641. sub _era_index { $_[0]->{local_c}{year} <= 0 ? 0 : 1 }
  642.  
  643. sub christian_era { $_[0]->ce_year > 0 ? 'AD' : 'BC' }
  644. sub secular_era   { $_[0]->ce_year > 0 ? 'CE' : 'BCE' }
  645.  
  646. sub year_with_era           { ( abs $_[0]->ce_year ) . $_[0]->era_abbr }
  647. sub year_with_christian_era { ( abs $_[0]->ce_year ) . $_[0]->christian_era }
  648. sub year_with_secular_era   { ( abs $_[0]->ce_year ) . $_[0]->secular_era }
  649.  
  650. sub month {
  651.     Carp::carp('month() is a read-only accessor') if @_ > 1;
  652.     return $_[0]->{local_c}{month};
  653. }
  654. *mon = \&month;
  655.  
  656. sub month_0 { $_[0]->{local_c}{month} - 1 }
  657. *mon_0 = \&month_0;
  658.  
  659. sub month_name { $_[0]->{locale}->month_format_wide->[ $_[0]->month_0() ] }
  660.  
  661. sub month_abbr {
  662.     $_[0]->{locale}->month_format_abbreviated->[ $_[0]->month_0() ];
  663. }
  664.  
  665. sub day_of_month {
  666.     Carp::carp('day_of_month() is a read-only accessor') if @_ > 1;
  667.     $_[0]->{local_c}{day};
  668. }
  669. *day  = \&day_of_month;
  670. *mday = \&day_of_month;
  671.  
  672. sub weekday_of_month { use integer; ( ( $_[0]->day - 1 ) / 7 ) + 1 }
  673.  
  674. sub quarter { $_[0]->{local_c}{quarter} }
  675.  
  676. sub quarter_name {
  677.     $_[0]->{locale}->quarter_format_wide->[ $_[0]->quarter_0() ];
  678. }
  679.  
  680. sub quarter_abbr {
  681.     $_[0]->{locale}->quarter_format_abbreviated->[ $_[0]->quarter_0() ];
  682. }
  683.  
  684. sub quarter_0 { $_[0]->{local_c}{quarter} - 1 }
  685.  
  686. sub day_of_month_0 { $_[0]->{local_c}{day} - 1 }
  687. *day_0  = \&day_of_month_0;
  688. *mday_0 = \&day_of_month_0;
  689.  
  690. sub day_of_week { $_[0]->{local_c}{day_of_week} }
  691. *wday = \&day_of_week;
  692. *dow  = \&day_of_week;
  693.  
  694. sub day_of_week_0 { $_[0]->{local_c}{day_of_week} - 1 }
  695. *wday_0 = \&day_of_week_0;
  696. *dow_0  = \&day_of_week_0;
  697.  
  698. sub local_day_of_week {
  699.     my $self = shift;
  700.  
  701.     my $day = $self->day_of_week();
  702.  
  703.     my $local_first_day = $self->{locale}->first_day_of_week();
  704.  
  705.     my $d = ( ( 8 - $local_first_day ) + $day ) % 7;
  706.  
  707.     return $d == 0 ? 7 : $d;
  708. }
  709.  
  710. sub day_name { $_[0]->{locale}->day_format_wide->[ $_[0]->day_of_week_0() ] }
  711.  
  712. sub day_abbr {
  713.     $_[0]->{locale}->day_format_abbreviated->[ $_[0]->day_of_week_0() ];
  714. }
  715.  
  716. sub day_of_quarter { $_[0]->{local_c}{day_of_quarter} }
  717. *doq = \&day_of_quarter;
  718.  
  719. sub day_of_quarter_0 { $_[0]->day_of_quarter - 1 }
  720. *doq_0 = \&day_of_quarter_0;
  721.  
  722. sub day_of_year { $_[0]->{local_c}{day_of_year} }
  723. *doy = \&day_of_year;
  724.  
  725. sub day_of_year_0 { $_[0]->{local_c}{day_of_year} - 1 }
  726. *doy_0 = \&day_of_year_0;
  727.  
  728. sub am_or_pm {
  729.     $_[0]->{locale}->am_pm_abbreviated->[ $_[0]->hour() < 12 ? 0 : 1 ];
  730. }
  731.  
  732. sub ymd {
  733.     my ( $self, $sep ) = @_;
  734.     $sep = '-' unless defined $sep;
  735.  
  736.     return sprintf(
  737.         "%0.4d%s%0.2d%s%0.2d",
  738.         $self->year,             $sep,
  739.         $self->{local_c}{month}, $sep,
  740.         $self->{local_c}{day}
  741.     );
  742. }
  743. *date = \&ymd;
  744.  
  745. sub mdy {
  746.     my ( $self, $sep ) = @_;
  747.     $sep = '-' unless defined $sep;
  748.  
  749.     return sprintf(
  750.         "%0.2d%s%0.2d%s%0.4d",
  751.         $self->{local_c}{month}, $sep,
  752.         $self->{local_c}{day},   $sep,
  753.         $self->year
  754.     );
  755. }
  756.  
  757. sub dmy {
  758.     my ( $self, $sep ) = @_;
  759.     $sep = '-' unless defined $sep;
  760.  
  761.     return sprintf(
  762.         "%0.2d%s%0.2d%s%0.4d",
  763.         $self->{local_c}{day},   $sep,
  764.         $self->{local_c}{month}, $sep,
  765.         $self->year
  766.     );
  767. }
  768.  
  769. sub hour {
  770.     Carp::carp('hour() is a read-only accessor') if @_ > 1;
  771.     return $_[0]->{local_c}{hour};
  772. }
  773. sub hour_1 { $_[0]->{local_c}{hour} == 0 ? 24 : $_[0]->{local_c}{hour} }
  774.  
  775. sub hour_12 { my $h = $_[0]->hour % 12; return $h ? $h : 12 }
  776. sub hour_12_0 { $_[0]->hour % 12 }
  777.  
  778. sub minute {
  779.     Carp::carp('minute() is a read-only accessor') if @_ > 1;
  780.     return $_[0]->{local_c}{minute};
  781. }
  782. *min = \&minute;
  783.  
  784. sub second {
  785.     Carp::carp('second() is a read-only accessor') if @_ > 1;
  786.     return $_[0]->{local_c}{second};
  787. }
  788. *sec = \&second;
  789.  
  790. sub fractional_second { $_[0]->second + $_[0]->nanosecond / MAX_NANOSECONDS }
  791.  
  792. sub nanosecond {
  793.     Carp::carp('nanosecond() is a read-only accessor') if @_ > 1;
  794.     return $_[0]->{rd_nanosecs};
  795. }
  796.  
  797. sub millisecond { _round( $_[0]->{rd_nanosecs} / 1000000 ) }
  798.  
  799. sub microsecond { _round( $_[0]->{rd_nanosecs} / 1000 ) }
  800.  
  801. sub _round {
  802.     my $val = shift;
  803.     my $int = int $val;
  804.  
  805.     return $val - $int >= 0.5 ? $int + 1 : $int;
  806. }
  807.  
  808. sub leap_seconds {
  809.     my $self = shift;
  810.  
  811.     return 0 if $self->{tz}->is_floating;
  812.  
  813.     return DateTime->_accumulated_leap_seconds( $self->{utc_rd_days} );
  814. }
  815.  
  816. sub _stringify {
  817.     my $self = shift;
  818.  
  819.     return $self->iso8601 unless $self->{formatter};
  820.     return $self->{formatter}->format_datetime($self);
  821. }
  822.  
  823. sub hms {
  824.     my ( $self, $sep ) = @_;
  825.     $sep = ':' unless defined $sep;
  826.  
  827.     return sprintf(
  828.         "%0.2d%s%0.2d%s%0.2d",
  829.         $self->{local_c}{hour},   $sep,
  830.         $self->{local_c}{minute}, $sep,
  831.         $self->{local_c}{second}
  832.     );
  833. }
  834.  
  835. # don't want to override CORE::time()
  836. *DateTime::time = \&hms;
  837.  
  838. sub iso8601 { join 'T', $_[0]->ymd('-'), $_[0]->hms(':') }
  839. *datetime = \&iso8601;
  840.  
  841. sub is_leap_year { $_[0]->_is_leap_year( $_[0]->year ) }
  842.  
  843. sub week {
  844.     my $self = shift;
  845.  
  846.     unless ( defined $self->{local_c}{week_year} ) {
  847.  
  848.         # This algorithm was taken from Date::Calc's DateCalc.c file
  849.         my $jan_one_dow_m1
  850.             = ( ( $self->_ymd2rd( $self->year, 1, 1 ) + 6 ) % 7 );
  851.  
  852.         $self->{local_c}{week_number}
  853.             = int( ( ( $self->day_of_year - 1 ) + $jan_one_dow_m1 ) / 7 );
  854.         $self->{local_c}{week_number}++ if $jan_one_dow_m1 < 4;
  855.  
  856.         if ( $self->{local_c}{week_number} == 0 ) {
  857.             $self->{local_c}{week_year} = $self->year - 1;
  858.             $self->{local_c}{week_number}
  859.                 = $self->_weeks_in_year( $self->{local_c}{week_year} );
  860.         }
  861.         elsif ($self->{local_c}{week_number} == 53
  862.             && $self->_weeks_in_year( $self->year ) == 52 ) {
  863.             $self->{local_c}{week_number} = 1;
  864.             $self->{local_c}{week_year}   = $self->year + 1;
  865.         }
  866.         else {
  867.             $self->{local_c}{week_year} = $self->year;
  868.         }
  869.     }
  870.  
  871.     return @{ $self->{local_c} }{ 'week_year', 'week_number' };
  872. }
  873.  
  874. # Also from DateCalc.c
  875. sub _weeks_in_year {
  876.     my $self = shift;
  877.     my $year = shift;
  878.  
  879.     my $jan_one_dow = ( ( $self->_ymd2rd( $year, 1,  1 ) + 6 ) % 7 ) + 1;
  880.     my $dec_31_dow  = ( ( $self->_ymd2rd( $year, 12, 31 ) + 6 ) % 7 ) + 1;
  881.  
  882.     return $jan_one_dow == 4 || $dec_31_dow == 4 ? 53 : 52;
  883. }
  884.  
  885. sub week_year   { ( $_[0]->week )[0] }
  886. sub week_number { ( $_[0]->week )[1] }
  887.  
  888. # ISO says that the first week of a year is the first week containing
  889. # a Thursday.  Extending that says that the first week of the month is
  890. # the first week containing a Thursday.  ICU agrees.
  891. #
  892. # Algorithm supplied by Rick Measham, who doesn't understand how it
  893. # works.  Neither do I.  Please feel free to explain this to me!
  894. sub week_of_month {
  895.     my $self = shift;
  896.  
  897.     # Faster than cloning just to get the dow
  898.     my $first_wday_of_month = ( 8 - ( $self->day - $self->dow ) % 7 ) % 7;
  899.     $first_wday_of_month = 7 unless $first_wday_of_month;
  900.  
  901.     my $wom = int( ( $self->day + $first_wday_of_month - 2 ) / 7 );
  902.     return ( $first_wday_of_month <= 4 ) ? $wom + 1 : $wom;
  903. }
  904.  
  905. sub time_zone {
  906.     Carp::carp('time_zone() is a read-only accessor') if @_ > 1;
  907.     return $_[0]->{tz};
  908. }
  909.  
  910. sub offset { $_[0]->{tz}->offset_for_datetime( $_[0] ) }
  911.  
  912. sub _offset_for_local_datetime {
  913.     $_[0]->{tz}->offset_for_local_datetime( $_[0] );
  914. }
  915.  
  916. sub is_dst { $_[0]->{tz}->is_dst_for_datetime( $_[0] ) }
  917.  
  918. sub time_zone_long_name  { $_[0]->{tz}->name }
  919. sub time_zone_short_name { $_[0]->{tz}->short_name_for_datetime( $_[0] ) }
  920.  
  921. sub locale {
  922.     Carp::carp('locale() is a read-only accessor') if @_ > 1;
  923.     return $_[0]->{locale};
  924. }
  925. *language = \&locale;
  926.  
  927. sub utc_rd_values {
  928.     @{ $_[0] }{ 'utc_rd_days', 'utc_rd_secs', 'rd_nanosecs' };
  929. }
  930.  
  931. sub local_rd_values {
  932.     @{ $_[0] }{ 'local_rd_days', 'local_rd_secs', 'rd_nanosecs' };
  933. }
  934.  
  935. # NOTE: no nanoseconds, no leap seconds
  936. sub utc_rd_as_seconds {
  937.     ( $_[0]->{utc_rd_days} * SECONDS_PER_DAY ) + $_[0]->{utc_rd_secs};
  938. }
  939.  
  940. # NOTE: no nanoseconds, no leap seconds
  941. sub local_rd_as_seconds {
  942.     ( $_[0]->{local_rd_days} * SECONDS_PER_DAY ) + $_[0]->{local_rd_secs};
  943. }
  944.  
  945. # RD 1 is JD 1,721,424.5 - a simple offset
  946. sub jd {
  947.     my $self = shift;
  948.  
  949.     my $jd = $self->{utc_rd_days} + 1_721_424.5;
  950.  
  951.     my $day_length = $self->_day_length( $self->{utc_rd_days} );
  952.  
  953.     return (  $jd
  954.             + ( $self->{utc_rd_secs} / $day_length )
  955.             + ( $self->{rd_nanosecs} / $day_length / MAX_NANOSECONDS ) );
  956. }
  957.  
  958. sub mjd { $_[0]->jd - 2_400_000.5 }
  959.  
  960. {
  961.     my %strftime_patterns = (
  962.         'a' => sub { $_[0]->day_abbr },
  963.         'A' => sub { $_[0]->day_name },
  964.         'b' => sub { $_[0]->month_abbr },
  965.         'B' => sub { $_[0]->month_name },
  966.         'c' => sub {
  967.             $_[0]->format_cldr( $_[0]->{locale}->datetime_format_default() );
  968.         },
  969.         'C' => sub { int( $_[0]->year / 100 ) },
  970.         'd' => sub { sprintf( '%02d', $_[0]->day_of_month ) },
  971.         'D' => sub { $_[0]->strftime('%m/%d/%y') },
  972.         'e' => sub { sprintf( '%2d', $_[0]->day_of_month ) },
  973.         'F' => sub { $_[0]->ymd('-') },
  974.         'g' => sub { substr( $_[0]->week_year, -2 ) },
  975.         'G' => sub { $_[0]->week_year },
  976.         'H' => sub { sprintf( '%02d', $_[0]->hour ) },
  977.         'I' => sub { sprintf( '%02d', $_[0]->hour_12 ) },
  978.         'j' => sub { $_[0]->day_of_year },
  979.         'k' => sub { sprintf( '%2d', $_[0]->hour ) },
  980.         'l' => sub { sprintf( '%2d', $_[0]->hour_12 ) },
  981.         'm' => sub { sprintf( '%02d', $_[0]->month ) },
  982.         'M' => sub { sprintf( '%02d', $_[0]->minute ) },
  983.         'n' => sub {"\n"},                     # should this be OS-sensitive?
  984.         'N' => \&_format_nanosecs,
  985.         'p' => sub { $_[0]->am_or_pm() },
  986.         'P' => sub { lc $_[0]->am_or_pm() },
  987.         'r' => sub { $_[0]->strftime('%I:%M:%S %p') },
  988.         'R' => sub { $_[0]->strftime('%H:%M') },
  989.         's' => sub { $_[0]->epoch },
  990.         'S' => sub { sprintf( '%02d', $_[0]->second ) },
  991.         't' => sub {"\t"},
  992.         'T' => sub { $_[0]->strftime('%H:%M:%S') },
  993.         'u' => sub { $_[0]->day_of_week },
  994.  
  995.         # algorithm from Date::Format::wkyr
  996.         'U' => sub {
  997.             my $dow = $_[0]->day_of_week;
  998.             $dow = 0 if $dow == 7;    # convert to 0-6, Sun-Sat
  999.             my $doy = $_[0]->day_of_year - 1;
  1000.             return sprintf( '%02d', int( ( $doy - $dow + 13 ) / 7 - 1 ) );
  1001.         },
  1002.         'V' => sub { sprintf( '%02d', $_[0]->week_number ) },
  1003.         'w' => sub {
  1004.             my $dow = $_[0]->day_of_week;
  1005.             return $dow % 7;
  1006.         },
  1007.         'W' => sub {
  1008.             my $dow = $_[0]->day_of_week;
  1009.             my $doy = $_[0]->day_of_year - 1;
  1010.             return sprintf( '%02d', int( ( $doy - $dow + 13 ) / 7 - 1 ) );
  1011.         },
  1012.         'x' => sub {
  1013.             $_[0]->format_cldr( $_[0]->{locale}->date_format_default() );
  1014.         },
  1015.         'X' => sub {
  1016.             $_[0]->format_cldr( $_[0]->{locale}->time_format_default() );
  1017.         },
  1018.         'y' => sub { sprintf( '%02d', substr( $_[0]->year, -2 ) ) },
  1019.         'Y' => sub { return $_[0]->year },
  1020.         'z' => sub { DateTime::TimeZone->offset_as_string( $_[0]->offset ) },
  1021.         'Z' => sub { $_[0]->{tz}->short_name_for_datetime( $_[0] ) },
  1022.         '%' => sub {'%'},
  1023.     );
  1024.  
  1025.     $strftime_patterns{h} = $strftime_patterns{b};
  1026.  
  1027.     sub strftime {
  1028.         my $self = shift;
  1029.  
  1030.         # make a copy or caller's scalars get munged
  1031.         my @patterns = @_;
  1032.  
  1033.         my @r;
  1034.         foreach my $p (@patterns) {
  1035.             $p =~ s/
  1036.                     (?:
  1037.                       %{(\w+)}         # method name like %{day_name}
  1038.                       |
  1039.                       %([%a-zA-Z])     # single character specifier like %d
  1040.                       |
  1041.                       %(\d+)N          # special case for %N
  1042.                     )
  1043.                    /
  1044.                     ( $1
  1045.                       ? ( $self->can($1) ? $self->$1() : "\%{$1}" )
  1046.                       : $2
  1047.                       ? ( $strftime_patterns{$2} ? $strftime_patterns{$2}->($self) : "\%$2" )
  1048.                       : $3
  1049.                       ? $strftime_patterns{N}->($self, $3)
  1050.                       : ''  # this won't happen
  1051.                     )
  1052.                    /sgex;
  1053.  
  1054.             return $p unless wantarray;
  1055.  
  1056.             push @r, $p;
  1057.         }
  1058.  
  1059.         return @r;
  1060.     }
  1061. }
  1062.  
  1063. {
  1064.  
  1065.     # It's an array because the order in which the regexes are checked
  1066.     # is important. These patterns are similar to the ones Java uses,
  1067.     # but not quite the same. See
  1068.     # http://www.unicode.org/reports/tr35/tr35-9.html#Date_Format_Patterns.
  1069.     my @patterns = (
  1070.         qr/GGGGG/ =>
  1071.             sub { $_[0]->{locale}->era_narrow->[ $_[0]->_era_index() ] },
  1072.         qr/GGGG/   => 'era_name',
  1073.         qr/G{1,3}/ => 'era_abbr',
  1074.  
  1075.         qr/(y{3,5})/ =>
  1076.             sub { $_[0]->_zero_padded_number( $1, $_[0]->year() ) },
  1077.  
  1078.         # yy is a weird special case, where it must be exactly 2 digits
  1079.         qr/yy/ => sub {
  1080.             my $year = $_[0]->year();
  1081.             my $y2 = substr( $year, -2, 2 ) if length $year > 2;
  1082.             $y2 *= -1 if $year < 0;
  1083.             $_[0]->_zero_padded_number( 'yy', $y2 );
  1084.         },
  1085.         qr/y/    => sub { $_[0]->year() },
  1086.         qr/(u+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->year() ) },
  1087.         qr/(Y+)/ =>
  1088.             sub { $_[0]->_zero_padded_number( $1, $_[0]->week_year() ) },
  1089.  
  1090.         qr/QQQQ/ => 'quarter_name',
  1091.         qr/QQQ/  => 'quarter_abbr',
  1092.         qr/(QQ?)/ =>
  1093.             sub { $_[0]->_zero_padded_number( $1, $_[0]->quarter() ) },
  1094.  
  1095.         qr/qqqq/ => sub {
  1096.             $_[0]->{locale}->quarter_stand_alone_wide()
  1097.                 ->[ $_[0]->quarter_0() ];
  1098.         },
  1099.         qr/qqq/ => sub {
  1100.             $_[0]->{locale}->quarter_stand_alone_abbreviated()
  1101.                 ->[ $_[0]->quarter_0() ];
  1102.         },
  1103.         qr/(qq?)/ =>
  1104.             sub { $_[0]->_zero_padded_number( $1, $_[0]->quarter() ) },
  1105.  
  1106.         qr/MMMMM/ =>
  1107.             sub { $_[0]->{locale}->month_format_narrow->[ $_[0]->month_0() ] }
  1108.         ,
  1109.         qr/MMMM/  => 'month_name',
  1110.         qr/MMM/   => 'month_abbr',
  1111.         qr/(MM?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->month() ) },
  1112.  
  1113.         qr/LLLLL/ => sub {
  1114.             $_[0]->{locale}->month_stand_alone_narrow->[ $_[0]->month_0() ];
  1115.         },
  1116.         qr/LLLL/ => sub {
  1117.             $_[0]->{locale}->month_stand_alone_wide->[ $_[0]->month_0() ];
  1118.         },
  1119.         qr/LLL/ => sub {
  1120.             $_[0]->{locale}
  1121.                 ->month_stand_alone_abbreviated->[ $_[0]->month_0() ];
  1122.         },
  1123.         qr/(LL?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->month() ) },
  1124.  
  1125.         qr/(ww?)/ =>
  1126.             sub { $_[0]->_zero_padded_number( $1, $_[0]->week_number() ) },
  1127.         qr/W/ => 'week_of_month',
  1128.  
  1129.         qr/(dd?)/ =>
  1130.             sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_month() ) },
  1131.         qr/(D{1,3})/ =>
  1132.             sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_year() ) },
  1133.  
  1134.         qr/F/    => 'weekday_of_month',
  1135.         qr/(g+)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->mjd() ) },
  1136.  
  1137.         qr/EEEEE/ => sub {
  1138.             $_[0]->{locale}->day_format_narrow->[ $_[0]->day_of_week_0() ];
  1139.         },
  1140.         qr/EEEE/   => 'day_name',
  1141.         qr/E{1,3}/ => 'day_abbr',
  1142.  
  1143.         qr/eeeee/ => sub {
  1144.             $_[0]->{locale}->day_format_narrow->[ $_[0]->day_of_week_0() ];
  1145.         },
  1146.         qr/eeee/  => 'day_name',
  1147.         qr/eee/   => 'day_abbr',
  1148.         qr/(ee?)/ => sub {
  1149.             $_[0]->_zero_padded_number( $1, $_[0]->local_day_of_week() );
  1150.         },
  1151.  
  1152.         qr/ccccc/ => sub {
  1153.             $_[0]->{locale}
  1154.                 ->day_stand_alone_narrow->[ $_[0]->day_of_week_0() ];
  1155.         },
  1156.         qr/cccc/ => sub {
  1157.             $_[0]->{locale}->day_stand_alone_wide->[ $_[0]->day_of_week_0() ];
  1158.         },
  1159.         qr/ccc/ => sub {
  1160.             $_[0]->{locale}
  1161.                 ->day_stand_alone_abbreviated->[ $_[0]->day_of_week_0() ];
  1162.         },
  1163.         qr/(cc?)/ =>
  1164.             sub { $_[0]->_zero_padded_number( $1, $_[0]->day_of_week() ) },
  1165.  
  1166.         qr/a/ => 'am_or_pm',
  1167.  
  1168.         qr/(hh?)/ =>
  1169.             sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_12() ) },
  1170.         qr/(HH?)/ => sub { $_[0]->_zero_padded_number( $1, $_[0]->hour() ) },
  1171.         qr/(KK?)/ =>
  1172.             sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_12_0() ) },
  1173.         qr/(kk?)/ =>
  1174.             sub { $_[0]->_zero_padded_number( $1, $_[0]->hour_1() ) },
  1175.         qr/(jj?)/ => sub {
  1176.             my $h
  1177.                 = $_[0]->{locale}->prefers_24_hour_time()
  1178.                 ? $_[0]->hour()
  1179.                 : $_[0]->hour_12();
  1180.             $_[0]->_zero_padded_number( $1, $h );
  1181.         },
  1182.  
  1183.         qr/(mm?)/ =>
  1184.             sub { $_[0]->_zero_padded_number( $1, $_[0]->minute() ) },
  1185.  
  1186.         qr/(ss?)/ =>
  1187.             sub { $_[0]->_zero_padded_number( $1, $_[0]->second() ) },
  1188.  
  1189.         # I'm not sure this is what is wanted (notably the trailing
  1190.         # and leading zeros it can produce), but once again the LDML
  1191.         # spec is not all that clear.
  1192.         qr/(S+)/ => sub {
  1193.             my $l   = length $1;
  1194.             my $val = sprintf( "%.${l}f",
  1195.                 $_[0]->fractional_second() - $_[0]->second() );
  1196.             $val =~ s/^0\.//;
  1197.             $val || 0;
  1198.         },
  1199.         qr/A+/ =>
  1200.             sub { ( $_[0]->{local_rd_secs} * 1000 ) + $_[0]->millisecond() },
  1201.  
  1202.         qr/zzzz/   => sub { $_[0]->time_zone_long_name() },
  1203.         qr/z{1,3}/ => sub { $_[0]->time_zone_short_name() },
  1204.         qr/ZZZZ/   => sub {
  1205.             $_[0]->time_zone_short_name()
  1206.                 . DateTime::TimeZone->offset_as_string( $_[0]->offset() );
  1207.         },
  1208.         qr/Z{1,3}/ =>
  1209.             sub { DateTime::TimeZone->offset_as_string( $_[0]->offset() ) },
  1210.         qr/vvvv/   => sub { $_[0]->time_zone_long_name() },
  1211.         qr/v{1,3}/ => sub { $_[0]->time_zone_short_name() },
  1212.         qr/VVVV/   => sub { $_[0]->time_zone_long_name() },
  1213.         qr/V{1,3}/ => sub { $_[0]->time_zone_short_name() },
  1214.     );
  1215.  
  1216.     sub _zero_padded_number {
  1217.         my $self = shift;
  1218.         my $size = length shift;
  1219.         my $val  = shift;
  1220.  
  1221.         return sprintf( "%0${size}d", $val );
  1222.     }
  1223.  
  1224.     sub _space_padded_string {
  1225.         my $self = shift;
  1226.         my $size = length shift;
  1227.         my $val  = shift;
  1228.  
  1229.         return sprintf( "% ${size}s", $val );
  1230.     }
  1231.  
  1232.     sub format_cldr {
  1233.         my $self = shift;
  1234.  
  1235.         # make a copy or caller's scalars get munged
  1236.         my @patterns = @_;
  1237.  
  1238.         my @r;
  1239.         foreach my $p (@patterns) {
  1240.             $p =~ s/\G
  1241.                     (?:
  1242.                       '((?:[^']|'')*)' # quote escaped bit of text
  1243.                                        # it needs to end with one
  1244.                                        # quote not followed by
  1245.                                        # another
  1246.                       |
  1247.                       (([a-zA-Z])\3*)     # could be a pattern
  1248.                       |
  1249.                       (.)                 # anything else
  1250.                     )
  1251.                    /
  1252.                     defined $1
  1253.                     ? $1
  1254.                     : defined $2
  1255.                     ? $self->_cldr_pattern($2)
  1256.                     : defined $4
  1257.                     ? $4
  1258.                     : undef # should never get here
  1259.                    /sgex;
  1260.  
  1261.             $p =~ s/\'\'/\'/g;
  1262.  
  1263.             return $p unless wantarray;
  1264.  
  1265.             push @r, $p;
  1266.         }
  1267.  
  1268.         return @r;
  1269.     }
  1270.  
  1271.     sub _cldr_pattern {
  1272.         my $self    = shift;
  1273.         my $pattern = shift;
  1274.  
  1275.         for ( my $i = 0; $i < @patterns; $i += 2 ) {
  1276.             if ( $pattern =~ /$patterns[$i]/ ) {
  1277.                 my $sub = $patterns[ $i + 1 ];
  1278.  
  1279.                 return $self->$sub();
  1280.             }
  1281.         }
  1282.  
  1283.         return $pattern;
  1284.     }
  1285. }
  1286.  
  1287. sub _format_nanosecs {
  1288.     my $self      = shift;
  1289.     my $precision = shift;
  1290.  
  1291.     my $ret = sprintf( "%09d", $self->{rd_nanosecs} );
  1292.     return $ret unless $precision;    # default = 9 digits
  1293.  
  1294.     # rd_nanosecs might contain a fractional separator
  1295.     my ( $int, $frac ) = split /[.,]/, $self->{rd_nanosecs};
  1296.     $ret .= $frac if $frac;
  1297.  
  1298.     return substr( $ret, 0, $precision );
  1299. }
  1300.  
  1301. sub epoch {
  1302.     my $self = shift;
  1303.  
  1304.     return $self->{utc_c}{epoch}
  1305.         if exists $self->{utc_c}{epoch};
  1306.  
  1307.     my ( $year, $month, $day ) = $self->_utc_ymd;
  1308.     my @hms = $self->_utc_hms;
  1309.  
  1310.     $self->{utc_c}{epoch} = timegm_nocheck(
  1311.         ( reverse @hms ),
  1312.         $day,
  1313.         $month - 1,
  1314.         $year,
  1315.     );
  1316.  
  1317.     return $self->{utc_c}{epoch};
  1318. }
  1319.  
  1320. sub hires_epoch {
  1321.     my $self = shift;
  1322.  
  1323.     my $epoch = $self->epoch;
  1324.  
  1325.     return undef unless defined $epoch;
  1326.  
  1327.     my $nano = $self->{rd_nanosecs} / MAX_NANOSECONDS;
  1328.  
  1329.     return $epoch + $nano;
  1330. }
  1331.  
  1332. sub is_finite   {1}
  1333. sub is_infinite {0}
  1334.  
  1335. # added for benefit of DateTime::TimeZone
  1336. sub utc_year { $_[0]->{utc_year} }
  1337.  
  1338. # returns a result that is relative to the first datetime
  1339. sub subtract_datetime {
  1340.     my $dt1 = shift;
  1341.     my $dt2 = shift;
  1342.  
  1343.     $dt2 = $dt2->clone->set_time_zone( $dt1->time_zone )
  1344.         unless $dt1->time_zone eq $dt2->time_zone;
  1345.  
  1346.     # We only want a negative duration if $dt2 > $dt1 ($self)
  1347.     my ( $bigger, $smaller, $negative ) = (
  1348.         $dt1 >= $dt2
  1349.         ? ( $dt1, $dt2, 0 )
  1350.         : ( $dt2, $dt1, 1 )
  1351.     );
  1352.  
  1353.     my $is_floating = $dt1->time_zone->is_floating
  1354.         && $dt2->time_zone->is_floating;
  1355.  
  1356.     my $minute_length = 60;
  1357.     unless ($is_floating) {
  1358.         my ( $utc_rd_days, $utc_rd_secs ) = $smaller->utc_rd_values;
  1359.  
  1360.         if ( $utc_rd_secs >= 86340 && !$is_floating ) {
  1361.  
  1362.             # If the smaller of the two datetimes occurs in the last
  1363.             # UTC minute of the UTC day, then that minute may not be
  1364.             # 60 seconds long.  If we need to subtract a minute from
  1365.             # the larger datetime's minutes count in order to adjust
  1366.             # the seconds difference to be positive, we need to know
  1367.             # how long that minute was.  If one of the datetimes is
  1368.             # floating, we just assume a minute is 60 seconds.
  1369.  
  1370.             $minute_length = $dt1->_day_length($utc_rd_days) - 86340;
  1371.         }
  1372.     }
  1373.  
  1374.     # This is a gross hack that basically figures out if the bigger of
  1375.     # the two datetimes is the day of a DST change.  If it's a 23 hour
  1376.     # day (switching _to_ DST) then we subtract 60 minutes from the
  1377.     # local time.  If it's a 25 hour day then we add 60 minutes to the
  1378.     # local time.
  1379.     #
  1380.     # This produces the most "intuitive" results, though there are
  1381.     # still reversibility problems with the resultant duration.
  1382.     #
  1383.     # However, if the two objects are on the same (local) date, and we
  1384.     # are not crossing a DST change, we don't want to invoke the hack
  1385.     # - see 38local-subtract.t
  1386.     my $bigger_min = $bigger->hour * 60 + $bigger->minute;
  1387.     if (   $bigger->time_zone->has_dst_changes
  1388.         && $bigger->is_dst != $smaller->is_dst ) {
  1389.  
  1390.         $bigger_min -= 60
  1391.  
  1392.             # it's a 23 hour (local) day
  1393.             if (
  1394.             $bigger->is_dst
  1395.             && do {
  1396.                 local $@;
  1397.                 my $prev_day = eval { $bigger->clone->subtract( days => 1 ) };
  1398.                 $prev_day && !$prev_day->is_dst ? 1 : 0;
  1399.             }
  1400.             );
  1401.  
  1402.         $bigger_min += 60
  1403.  
  1404.             # it's a 25 hour (local) day
  1405.             if (
  1406.             !$bigger->is_dst
  1407.             && do {
  1408.                 local $@;
  1409.                 my $prev_day = eval { $bigger->clone->subtract( days => 1 ) };
  1410.                 $prev_day && $prev_day->is_dst ? 1 : 0;
  1411.             }
  1412.             );
  1413.     }
  1414.  
  1415.     my ( $months, $days, $minutes, $seconds, $nanoseconds )
  1416.         = $dt1->_adjust_for_positive_difference(
  1417.         $bigger->year * 12 + $bigger->month,
  1418.         $smaller->year * 12 + $smaller->month,
  1419.  
  1420.         $bigger->day, $smaller->day,
  1421.  
  1422.         $bigger_min, $smaller->hour * 60 + $smaller->minute,
  1423.  
  1424.         $bigger->second, $smaller->second,
  1425.  
  1426.         $bigger->nanosecond, $smaller->nanosecond,
  1427.  
  1428.         $minute_length,
  1429.  
  1430.         # XXX - using the smaller as the month length is
  1431.         # somewhat arbitrary, we could also use the bigger -
  1432.         # either way we have reversibility problems
  1433.         $dt1->_month_length( $smaller->year, $smaller->month ),
  1434.         );
  1435.  
  1436.     if ($negative) {
  1437.         for ( $months, $days, $minutes, $seconds, $nanoseconds ) {
  1438.  
  1439.             # Some versions of Perl can end up with -0 if we do "0 * -1"!!
  1440.             $_ *= -1 if $_;
  1441.         }
  1442.     }
  1443.  
  1444.     return $dt1->duration_class->new(
  1445.         months      => $months,
  1446.         days        => $days,
  1447.         minutes     => $minutes,
  1448.         seconds     => $seconds,
  1449.         nanoseconds => $nanoseconds,
  1450.     );
  1451. }
  1452.  
  1453. sub _adjust_for_positive_difference {
  1454.     my (
  1455.         $self,
  1456.         $month1, $month2,
  1457.         $day1,   $day2,
  1458.         $min1,   $min2,
  1459.         $sec1,   $sec2,
  1460.         $nano1,  $nano2,
  1461.         $minute_length,
  1462.         $month_length,
  1463.     ) = @_;
  1464.  
  1465.     if ( $nano1 < $nano2 ) {
  1466.         $sec1--;
  1467.         $nano1 += MAX_NANOSECONDS;
  1468.     }
  1469.  
  1470.     if ( $sec1 < $sec2 ) {
  1471.         $min1--;
  1472.         $sec1 += $minute_length;
  1473.     }
  1474.  
  1475.     # A day always has 24 * 60 minutes, though the minutes may vary in
  1476.     # length.
  1477.     if ( $min1 < $min2 ) {
  1478.         $day1--;
  1479.         $min1 += 24 * 60;
  1480.     }
  1481.  
  1482.     if ( $day1 < $day2 ) {
  1483.         $month1--;
  1484.         $day1 += $month_length;
  1485.     }
  1486.  
  1487.     return (
  1488.         $month1 - $month2,
  1489.         $day1 - $day2,
  1490.         $min1 - $min2,
  1491.         $sec1 - $sec2,
  1492.         $nano1 - $nano2,
  1493.     );
  1494. }
  1495.  
  1496. sub subtract_datetime_absolute {
  1497.     my $self = shift;
  1498.     my $dt   = shift;
  1499.  
  1500.     my $utc_rd_secs1 = $self->utc_rd_as_seconds;
  1501.     $utc_rd_secs1
  1502.         += DateTime->_accumulated_leap_seconds( $self->{utc_rd_days} )
  1503.         if !$self->time_zone->is_floating;
  1504.  
  1505.     my $utc_rd_secs2 = $dt->utc_rd_as_seconds;
  1506.     $utc_rd_secs2 += DateTime->_accumulated_leap_seconds( $dt->{utc_rd_days} )
  1507.         if !$dt->time_zone->is_floating;
  1508.  
  1509.     my $seconds     = $utc_rd_secs1 - $utc_rd_secs2;
  1510.     my $nanoseconds = $self->nanosecond - $dt->nanosecond;
  1511.  
  1512.     if ( $nanoseconds < 0 ) {
  1513.         $seconds--;
  1514.         $nanoseconds += MAX_NANOSECONDS;
  1515.     }
  1516.  
  1517.     return $self->duration_class->new(
  1518.         seconds     => $seconds,
  1519.         nanoseconds => $nanoseconds,
  1520.     );
  1521. }
  1522.  
  1523. sub delta_md {
  1524.     my $self = shift;
  1525.     my $dt   = shift;
  1526.  
  1527.     my ( $smaller, $bigger ) = sort $self, $dt;
  1528.  
  1529.     my ( $months, $days, undef, undef, undef )
  1530.         = $dt->_adjust_for_positive_difference(
  1531.         $bigger->year * 12 + $bigger->month,
  1532.         $smaller->year * 12 + $smaller->month,
  1533.  
  1534.         $bigger->day, $smaller->day,
  1535.  
  1536.         0, 0,
  1537.  
  1538.         0, 0,
  1539.  
  1540.         0, 0,
  1541.  
  1542.         60,
  1543.  
  1544.         $smaller->_month_length( $smaller->year, $smaller->month ),
  1545.         );
  1546.  
  1547.     return $self->duration_class->new(
  1548.         months => $months,
  1549.         days   => $days
  1550.     );
  1551. }
  1552.  
  1553. sub delta_days {
  1554.     my $self = shift;
  1555.     my $dt   = shift;
  1556.  
  1557.     my $days
  1558.         = abs( ( $self->local_rd_values )[0] - ( $dt->local_rd_values )[0] );
  1559.  
  1560.     $self->duration_class->new( days => $days );
  1561. }
  1562.  
  1563. sub delta_ms {
  1564.     my $self = shift;
  1565.     my $dt   = shift;
  1566.  
  1567.     my ( $smaller, $greater ) = sort $self, $dt;
  1568.  
  1569.     my $days = int( $greater->jd - $smaller->jd );
  1570.  
  1571.     my $dur = $greater->subtract_datetime($smaller);
  1572.  
  1573.     my %p;
  1574.     $p{hours}   = $dur->hours + ( $days * 24 );
  1575.     $p{minutes} = $dur->minutes;
  1576.     $p{seconds} = $dur->seconds;
  1577.  
  1578.     return $self->duration_class->new(%p);
  1579. }
  1580.  
  1581. sub _add_overload {
  1582.     my ( $dt, $dur, $reversed ) = @_;
  1583.  
  1584.     if ($reversed) {
  1585.         ( $dur, $dt ) = ( $dt, $dur );
  1586.     }
  1587.  
  1588.     unless ( DateTime::Helpers::isa( $dur, 'DateTime::Duration' ) ) {
  1589.         my $class     = ref $dt;
  1590.         my $dt_string = overload::StrVal($dt);
  1591.  
  1592.         Carp::croak( "Cannot add $dur to a $class object ($dt_string).\n"
  1593.                 . " Only a DateTime::Duration object can "
  1594.                 . " be added to a $class object." );
  1595.     }
  1596.  
  1597.     return $dt->clone->add_duration($dur);
  1598. }
  1599.  
  1600. sub _subtract_overload {
  1601.     my ( $date1, $date2, $reversed ) = @_;
  1602.  
  1603.     if ($reversed) {
  1604.         ( $date2, $date1 ) = ( $date1, $date2 );
  1605.     }
  1606.  
  1607.     if ( DateTime::Helpers::isa( $date2, 'DateTime::Duration' ) ) {
  1608.         my $new = $date1->clone;
  1609.         $new->add_duration( $date2->inverse );
  1610.         return $new;
  1611.     }
  1612.     elsif ( DateTime::Helpers::isa( $date2, 'DateTime' ) ) {
  1613.         return $date1->subtract_datetime($date2);
  1614.     }
  1615.     else {
  1616.         my $class     = ref $date1;
  1617.         my $dt_string = overload::StrVal($date1);
  1618.  
  1619.         Carp::croak(
  1620.             "Cannot subtract $date2 from a $class object ($dt_string).\n"
  1621.                 . " Only a DateTime::Duration or DateTime object can "
  1622.                 . " be subtracted from a $class object." );
  1623.     }
  1624. }
  1625.  
  1626. sub add {
  1627.     my $self = shift;
  1628.  
  1629.     return $self->add_duration( $self->duration_class->new(@_) );
  1630. }
  1631.  
  1632. sub subtract {
  1633.     my $self = shift;
  1634.  
  1635.     return $self->subtract_duration( $self->duration_class->new(@_) );
  1636. }
  1637.  
  1638. sub subtract_duration { return $_[0]->add_duration( $_[1]->inverse ) }
  1639.  
  1640. {
  1641.     my @spec = ( { isa => 'DateTime::Duration' } );
  1642.  
  1643.     sub add_duration {
  1644.         my $self = shift;
  1645.         my ($dur) = validate_pos( @_, @spec );
  1646.  
  1647.         # simple optimization
  1648.         return $self if $dur->is_zero;
  1649.  
  1650.         my %deltas = $dur->deltas;
  1651.  
  1652.         # This bit isn't quite right since DateTime::Infinite::Future -
  1653.         # infinite duration should NaN
  1654.         foreach my $val ( values %deltas ) {
  1655.             my $inf;
  1656.             if ( $val == INFINITY ) {
  1657.                 $inf = DateTime::Infinite::Future->new;
  1658.             }
  1659.             elsif ( $val == NEG_INFINITY ) {
  1660.                 $inf = DateTime::Infinite::Past->new;
  1661.             }
  1662.  
  1663.             if ($inf) {
  1664.                 %$self = %$inf;
  1665.                 bless $self, ref $inf;
  1666.  
  1667.                 return $self;
  1668.             }
  1669.         }
  1670.  
  1671.         return $self if $self->is_infinite;
  1672.  
  1673.         if ( $deltas{days} ) {
  1674.             $self->{local_rd_days} += $deltas{days};
  1675.  
  1676.             $self->{utc_year} += int( $deltas{days} / 365 ) + 1;
  1677.         }
  1678.  
  1679.         if ( $deltas{months} ) {
  1680.  
  1681.             # For preserve mode, if it is the last day of the month, make
  1682.             # it the 0th day of the following month (which then will
  1683.             # normalize back to the last day of the new month).
  1684.             my ( $y, $m, $d ) = (
  1685.                   $dur->is_preserve_mode
  1686.                 ? $self->_rd2ymd( $self->{local_rd_days} + 1 )
  1687.                 : $self->_rd2ymd( $self->{local_rd_days} )
  1688.             );
  1689.  
  1690.             $d -= 1 if $dur->is_preserve_mode;
  1691.  
  1692.             if ( !$dur->is_wrap_mode && $d > 28 ) {
  1693.  
  1694.                 # find the rd for the last day of our target month
  1695.                 $self->{local_rd_days}
  1696.                     = $self->_ymd2rd( $y, $m + $deltas{months} + 1, 0 );
  1697.  
  1698.                 # what day of the month is it? (discard year and month)
  1699.                 my $last_day
  1700.                     = ( $self->_rd2ymd( $self->{local_rd_days} ) )[2];
  1701.  
  1702.                 # if our original day was less than the last day,
  1703.                 # use that instead
  1704.                 $self->{local_rd_days} -= $last_day - $d if $last_day > $d;
  1705.             }
  1706.             else {
  1707.                 $self->{local_rd_days}
  1708.                     = $self->_ymd2rd( $y, $m + $deltas{months}, $d );
  1709.             }
  1710.  
  1711.             $self->{utc_year} += int( $deltas{months} / 12 ) + 1;
  1712.         }
  1713.  
  1714.         if ( $deltas{days} || $deltas{months} ) {
  1715.             $self->_calc_utc_rd;
  1716.  
  1717.             $self->_handle_offset_modifier( $self->second );
  1718.         }
  1719.  
  1720.         if ( $deltas{minutes} ) {
  1721.             $self->{utc_rd_secs} += $deltas{minutes} * 60;
  1722.  
  1723.             # This intentionally ignores leap seconds
  1724.             $self->_normalize_tai_seconds( $self->{utc_rd_days},
  1725.                 $self->{utc_rd_secs} );
  1726.         }
  1727.  
  1728.         if ( $deltas{seconds} || $deltas{nanoseconds} ) {
  1729.             $self->{utc_rd_secs} += $deltas{seconds};
  1730.  
  1731.             if ( $deltas{nanoseconds} ) {
  1732.                 $self->{rd_nanosecs} += $deltas{nanoseconds};
  1733.                 $self->_normalize_nanoseconds( $self->{utc_rd_secs},
  1734.                     $self->{rd_nanosecs} );
  1735.             }
  1736.  
  1737.             $self->_normalize_seconds;
  1738.  
  1739.             # This might be some big number much bigger than 60, but
  1740.             # that's ok (there are tests in 19leap_second.t to confirm
  1741.             # that)
  1742.             $self->_handle_offset_modifier(
  1743.                 $self->second + $deltas{seconds} );
  1744.         }
  1745.  
  1746.         my $new = ( ref $self )->from_object(
  1747.             object => $self,
  1748.             locale => $self->{locale},
  1749.             ( $self->{formatter} ? ( formatter => $self->{formatter} ) : () ),
  1750.         );
  1751.  
  1752.         %$self = %$new;
  1753.  
  1754.         return $self;
  1755.     }
  1756. }
  1757.  
  1758. sub _compare_overload {
  1759.  
  1760.     # note: $_[1]->compare( $_[0] ) is an error when $_[1] is not a
  1761.     # DateTime (such as the INFINITY value)
  1762.     return $_[2] ? -$_[0]->compare( $_[1] ) : $_[0]->compare( $_[1] );
  1763. }
  1764.  
  1765. sub _string_compare_overload {
  1766.     my ( $dt1, $dt2, $flip ) = @_;
  1767.  
  1768.     # One is a DateTime object, one isn't.  Just stringify and compare.
  1769.     if ( !DateTime::Helpers::can( $dt2, 'utc_rd_values' ) ) {
  1770.         my $sign = $flip ? -1 : 1;
  1771.         return $sign * ( "$dt1" cmp "$dt2" );
  1772.     }
  1773.     else {
  1774.         my $meth = $dt1->can('_compare_overload');
  1775.         goto $meth;
  1776.     }
  1777. }
  1778.  
  1779. sub compare {
  1780.     shift->_compare( @_, 0 );
  1781. }
  1782.  
  1783. sub compare_ignore_floating {
  1784.     shift->_compare( @_, 1 );
  1785. }
  1786.  
  1787. sub _compare {
  1788.     my ( $class, $dt1, $dt2, $consistent ) = ref $_[0] ? ( undef, @_ ) : @_;
  1789.  
  1790.     return undef unless defined $dt2;
  1791.  
  1792.     if ( !ref $dt2 && ( $dt2 == INFINITY || $dt2 == NEG_INFINITY ) ) {
  1793.         return $dt1->{utc_rd_days} <=> $dt2;
  1794.     }
  1795.  
  1796.     unless ( DateTime::Helpers::can( $dt1, 'utc_rd_values' )
  1797.         && DateTime::Helpers::can( $dt2, 'utc_rd_values' ) ) {
  1798.         my $dt1_string = overload::StrVal($dt1);
  1799.         my $dt2_string = overload::StrVal($dt2);
  1800.  
  1801.         Carp::croak( "A DateTime object can only be compared to"
  1802.                 . " another DateTime object ($dt1_string, $dt2_string)." );
  1803.     }
  1804.  
  1805.     if (   !$consistent
  1806.         && DateTime::Helpers::can( $dt1, 'time_zone' )
  1807.         && DateTime::Helpers::can( $dt2, 'time_zone' ) ) {
  1808.         my $is_floating1 = $dt1->time_zone->is_floating;
  1809.         my $is_floating2 = $dt2->time_zone->is_floating;
  1810.  
  1811.         if ( $is_floating1 && !$is_floating2 ) {
  1812.             $dt1 = $dt1->clone->set_time_zone( $dt2->time_zone );
  1813.         }
  1814.         elsif ( $is_floating2 && !$is_floating1 ) {
  1815.             $dt2 = $dt2->clone->set_time_zone( $dt1->time_zone );
  1816.         }
  1817.     }
  1818.  
  1819.     my @dt1_components = $dt1->utc_rd_values;
  1820.     my @dt2_components = $dt2->utc_rd_values;
  1821.  
  1822.     foreach my $i ( 0 .. 2 ) {
  1823.         return $dt1_components[$i] <=> $dt2_components[$i]
  1824.             if $dt1_components[$i] != $dt2_components[$i];
  1825.     }
  1826.  
  1827.     return 0;
  1828. }
  1829.  
  1830. sub _string_equals_overload {
  1831.     my ( $class, $dt1, $dt2 ) = ref $_[0] ? ( undef, @_ ) : @_;
  1832.  
  1833.     if ( !DateTime::Helpers::can( $dt2, 'utc_rd_values' ) ) {
  1834.         return "$dt1" eq "$dt2";
  1835.     }
  1836.  
  1837.     $class ||= ref $dt1;
  1838.     return !$class->compare( $dt1, $dt2 );
  1839. }
  1840.  
  1841. sub _string_not_equals_overload {
  1842.     return !_string_equals_overload(@_);
  1843. }
  1844.  
  1845. sub _normalize_nanoseconds {
  1846.     use integer;
  1847.  
  1848.     # seconds, nanoseconds
  1849.     if ( $_[2] < 0 ) {
  1850.         my $overflow = 1 + $_[2] / MAX_NANOSECONDS;
  1851.         $_[2] += $overflow * MAX_NANOSECONDS;
  1852.         $_[1] -= $overflow;
  1853.     }
  1854.     elsif ( $_[2] >= MAX_NANOSECONDS ) {
  1855.         my $overflow = $_[2] / MAX_NANOSECONDS;
  1856.         $_[2] -= $overflow * MAX_NANOSECONDS;
  1857.         $_[1] += $overflow;
  1858.     }
  1859. }
  1860.  
  1861. # Many of the same parameters as new() but all of them are optional,
  1862. # and there are no defaults.
  1863. my $SetValidate = {
  1864.     map {
  1865.         my %copy = %{ $BasicValidate->{$_} };
  1866.         delete $copy{default};
  1867.         $copy{optional} = 1;
  1868.         $_ => \%copy
  1869.         }
  1870.         keys %$BasicValidate
  1871. };
  1872.  
  1873. sub set {
  1874.     my $self = shift;
  1875.     my %p = validate( @_, $SetValidate );
  1876.  
  1877.     my $new_dt = $self->_new_from_self(%p);
  1878.  
  1879.     %$self = %$new_dt;
  1880.  
  1881.     return $self;
  1882. }
  1883.  
  1884. sub set_year       { $_[0]->set( year       => $_[1] ) }
  1885. sub set_month      { $_[0]->set( month      => $_[1] ) }
  1886. sub set_day        { $_[0]->set( day        => $_[1] ) }
  1887. sub set_hour       { $_[0]->set( hour       => $_[1] ) }
  1888. sub set_minute     { $_[0]->set( minute     => $_[1] ) }
  1889. sub set_second     { $_[0]->set( second     => $_[1] ) }
  1890. sub set_nanosecond { $_[0]->set( nanosecond => $_[1] ) }
  1891. sub set_locale     { $_[0]->set( locale     => $_[1] ) }
  1892. sub set_formatter  { $_[0]->set( formatter  => $_[1] ) }
  1893.  
  1894. {
  1895.     my %TruncateDefault = (
  1896.         month      => 1,
  1897.         day        => 1,
  1898.         hour       => 0,
  1899.         minute     => 0,
  1900.         second     => 0,
  1901.         nanosecond => 0,
  1902.     );
  1903.     my $re = join '|', 'year', 'week',
  1904.         grep { $_ ne 'nanosecond' } keys %TruncateDefault;
  1905.     my $spec = { to => { regex => qr/^(?:$re)/ } };
  1906.  
  1907.     sub truncate {
  1908.         my $self = shift;
  1909.         my %p = validate( @_, $spec );
  1910.  
  1911.         my %new;
  1912.         if ( $p{to} eq 'week' ) {
  1913.             my $day_diff = $self->day_of_week - 1;
  1914.  
  1915.             if ($day_diff) {
  1916.                 $self->add( days => -1 * $day_diff );
  1917.             }
  1918.  
  1919.             return $self->truncate( to => 'day' );
  1920.         }
  1921.         else {
  1922.             my $truncate;
  1923.             foreach my $f (qw( year month day hour minute second nanosecond ))
  1924.             {
  1925.                 $new{$f} = $truncate ? $TruncateDefault{$f} : $self->$f();
  1926.  
  1927.                 $truncate = 1 if $p{to} eq $f;
  1928.             }
  1929.         }
  1930.  
  1931.         my $new_dt = $self->_new_from_self(%new);
  1932.  
  1933.         %$self = %$new_dt;
  1934.  
  1935.         return $self;
  1936.     }
  1937. }
  1938.  
  1939. sub set_time_zone {
  1940.     my ( $self, $tz ) = @_;
  1941.  
  1942.     # This is a bit of a hack but it works because time zone objects
  1943.     # are singletons, and if it doesn't work all we lose is a little
  1944.     # bit of speed.
  1945.     return $self if $self->{tz} eq $tz;
  1946.  
  1947.     my $was_floating = $self->{tz}->is_floating;
  1948.  
  1949.     $self->{tz} = ref $tz ? $tz : DateTime::TimeZone->new( name => $tz );
  1950.  
  1951.     $self->_handle_offset_modifier( $self->second, 1 );
  1952.  
  1953.     # if it either was or now is floating (but not both)
  1954.     if ( $self->{tz}->is_floating xor $was_floating ) {
  1955.         $self->_calc_utc_rd;
  1956.     }
  1957.     elsif ( !$was_floating ) {
  1958.         $self->_calc_local_rd;
  1959.     }
  1960.  
  1961.     return $self;
  1962. }
  1963.  
  1964. sub STORABLE_freeze {
  1965.     my $self    = shift;
  1966.     my $cloning = shift;
  1967.  
  1968.     my $serialized = '';
  1969.     foreach my $key (
  1970.         qw( utc_rd_days
  1971.         utc_rd_secs
  1972.         rd_nanosecs )
  1973.         ) {
  1974.         $serialized .= "$key:$self->{$key}|";
  1975.     }
  1976.  
  1977.     # not used yet, but may be handy in the future.
  1978.     $serialized .= "version:$DateTime::VERSION";
  1979.  
  1980.     # Formatter needs to be returned as a reference since it may be
  1981.     # undef or a class name, and Storable will complain if extra
  1982.     # return values aren't refs
  1983.     return $serialized, $self->{locale}, $self->{tz}, \$self->{formatter};
  1984. }
  1985.  
  1986. sub STORABLE_thaw {
  1987.     my $self       = shift;
  1988.     my $cloning    = shift;
  1989.     my $serialized = shift;
  1990.  
  1991.     my %serialized = map { split /:/ } split /\|/, $serialized;
  1992.  
  1993.     my ( $locale, $tz, $formatter );
  1994.  
  1995.     # more recent code version
  1996.     if (@_) {
  1997.         ( $locale, $tz, $formatter ) = @_;
  1998.     }
  1999.     else {
  2000.         $tz = DateTime::TimeZone->new( name => delete $serialized{tz} );
  2001.  
  2002.         $locale = DateTime::Locale->load(
  2003.             exists $serialized{language}
  2004.             ? delete $serialized{language}
  2005.             : delete $serialized{locale}
  2006.         );
  2007.     }
  2008.  
  2009.     delete $serialized{version};
  2010.  
  2011.     my $object = bless {
  2012.         utc_vals => [
  2013.             $serialized{utc_rd_days},
  2014.             $serialized{utc_rd_secs},
  2015.             $serialized{rd_nanosecs},
  2016.         ],
  2017.         tz => $tz,
  2018.         },
  2019.         'DateTime::_Thawed';
  2020.  
  2021.     my %formatter = defined $$formatter ? ( formatter => $$formatter ) : ();
  2022.     my $new = ( ref $self )->from_object(
  2023.         object => $object,
  2024.         locale => $locale,
  2025.         %formatter,
  2026.     );
  2027.  
  2028.     %$self = %$new;
  2029.  
  2030.     return $self;
  2031. }
  2032.  
  2033. package DateTime::_Thawed;
  2034. BEGIN {
  2035.   $DateTime::_Thawed::VERSION = '0.61';
  2036. }
  2037.  
  2038. sub utc_rd_values { @{ $_[0]->{utc_vals} } }
  2039.  
  2040. sub time_zone { $_[0]->{tz} }
  2041.  
  2042. 1;
  2043.  
  2044. # ABSTRACT: A date and time object
  2045.  
  2046.  
  2047.  
  2048. =pod
  2049.  
  2050. =head1 NAME
  2051.  
  2052. DateTime - A date and time object
  2053.  
  2054. =head1 VERSION
  2055.  
  2056. version 0.61
  2057.  
  2058. =head1 SYNOPSIS
  2059.  
  2060.   use DateTime;
  2061.  
  2062.   $dt = DateTime->new( year   => 1964,
  2063.                        month  => 10,
  2064.                        day    => 16,
  2065.                        hour   => 16,
  2066.                        minute => 12,
  2067.                        second => 47,
  2068.                        nanosecond => 500000000,
  2069.                        time_zone => 'Asia/Taipei',
  2070.                      );
  2071.  
  2072.   $dt = DateTime->from_epoch( epoch => $epoch );
  2073.   $dt = DateTime->now; # same as ( epoch => time() )
  2074.  
  2075.   $year   = $dt->year;
  2076.   $month  = $dt->month;          # 1-12 - also mon
  2077.  
  2078.   $day    = $dt->day;            # 1-31 - also day_of_month, mday
  2079.  
  2080.   $dow    = $dt->day_of_week;    # 1-7 (Monday is 1) - also dow, wday
  2081.  
  2082.   $hour   = $dt->hour;           # 0-23
  2083.   $minute = $dt->minute;         # 0-59 - also min
  2084.  
  2085.   $second = $dt->second;         # 0-61 (leap seconds!) - also sec
  2086.  
  2087.   $doy    = $dt->day_of_year;    # 1-366 (leap years) - also doy
  2088.  
  2089.   $doq    = $dt->day_of_quarter; # 1.. - also doq
  2090.  
  2091.   $qtr    = $dt->quarter;        # 1-4
  2092.  
  2093.   # all of the start-at-1 methods above have corresponding start-at-0
  2094.   # methods, such as $dt->day_of_month_0, $dt->month_0 and so on
  2095.  
  2096.   $ymd    = $dt->ymd;           # 2002-12-06
  2097.   $ymd    = $dt->ymd('/');      # 2002/12/06 - also date
  2098.  
  2099.   $mdy    = $dt->mdy;           # 12-06-2002
  2100.   $mdy    = $dt->mdy('/');      # 12/06/2002
  2101.  
  2102.   $dmy    = $dt->dmy;           # 06-12-2002
  2103.   $dmy    = $dt->dmy('/');      # 06/12/2002
  2104.  
  2105.   $hms    = $dt->hms;           # 14:02:29
  2106.   $hms    = $dt->hms('!');      # 14!02!29 - also time
  2107.  
  2108.   $is_leap  = $dt->is_leap_year;
  2109.  
  2110.   # these are localizable, see Locales section
  2111.   $month_name  = $dt->month_name; # January, February, ...
  2112.   $month_abbr  = $dt->month_abbr; # Jan, Feb, ...
  2113.   $day_name    = $dt->day_name;   # Monday, Tuesday, ...
  2114.   $day_abbr    = $dt->day_abbr;   # Mon, Tue, ...
  2115.  
  2116.   # May not work for all possible datetime, see the docs on this
  2117.   # method for more details.
  2118.   $epoch_time  = $dt->epoch;
  2119.  
  2120.   $dt2 = $dt + $duration_object;
  2121.  
  2122.   $dt3 = $dt - $duration_object;
  2123.  
  2124.   $duration_object = $dt - $dt2;
  2125.  
  2126.   $dt->set( year => 1882 );
  2127.  
  2128.   $dt->set_time_zone( 'America/Chicago' );
  2129.  
  2130.   $dt->set_formatter( $formatter );
  2131.  
  2132. =head1 DESCRIPTION
  2133.  
  2134. DateTime is a class for the representation of date/time combinations,
  2135. and is part of the Perl DateTime project.  For details on this project
  2136. please see L<http://datetime.perl.org/>.  The DateTime site has a FAQ
  2137. which may help answer many "how do I do X?" questions.  The FAQ is at
  2138. L<http://datetime.perl.org/?FAQ>.
  2139.  
  2140. It represents the Gregorian calendar, extended backwards in time
  2141. before its creation (in 1582).  This is sometimes known as the
  2142. "proleptic Gregorian calendar".  In this calendar, the first day of
  2143. the calendar (the epoch), is the first day of year 1, which
  2144. corresponds to the date which was (incorrectly) believed to be the
  2145. birth of Jesus Christ.
  2146.  
  2147. The calendar represented does have a year 0, and in that way differs
  2148. from how dates are often written using "BCE/CE" or "BC/AD".
  2149.  
  2150. For infinite datetimes, please see the
  2151. L<DateTime::Infinite|DateTime::Infinite> module.
  2152.  
  2153. =head1 USAGE
  2154.  
  2155. =head2 0-based Versus 1-based Numbers
  2156.  
  2157. The DateTime.pm module follows a simple consistent logic for
  2158. determining whether or not a given number is 0-based or 1-based.
  2159.  
  2160. Month, day of month, day of week, and day of year are 1-based.  Any
  2161. method that is 1-based also has an equivalent 0-based method ending in
  2162. "_0".  So for example, this class provides both C<day_of_week()> and
  2163. C<day_of_week_0()> methods.
  2164.  
  2165. The C<day_of_week_0()> method still treats Monday as the first day of
  2166. the week.
  2167.  
  2168. All I<time>-related numbers such as hour, minute, and second are
  2169. 0-based.
  2170.  
  2171. Years are neither, as they can be both positive or negative, unlike
  2172. any other datetime component.  There I<is> a year 0.
  2173.  
  2174. There is no C<quarter_0()> method.
  2175.  
  2176. =head2 Error Handling
  2177.  
  2178. Some errors may cause this module to die with an error string.  This
  2179. can only happen when calling constructor methods, methods that change
  2180. the object, such as C<set()>, or methods that take parameters.
  2181. Methods that retrieve information about the object, such as C<year()>
  2182. or C<epoch()>, will never die.
  2183.  
  2184. =head2 Locales
  2185.  
  2186. All the object methods which return names or abbreviations return data
  2187. based on a locale.  This is done by setting the locale when
  2188. constructing a DateTime object.  There is also a C<DefaultLocale()>
  2189. class method which may be used to set the default locale for all
  2190. DateTime objects created.  If this is not set, then "en_US" is used.
  2191.  
  2192. =head2 Floating DateTimes
  2193.  
  2194. The default time zone for new DateTime objects, except where stated
  2195. otherwise, is the "floating" time zone.  This concept comes from the
  2196. iCal standard.  A floating datetime is one which is not anchored to
  2197. any particular time zone.  In addition, floating datetimes do not
  2198. include leap seconds, since we cannot apply them without knowing the
  2199. datetime's time zone.
  2200.  
  2201. The results of date math and comparison between a floating datetime
  2202. and one with a real time zone are not really valid, because one
  2203. includes leap seconds and the other does not.  Similarly, the results
  2204. of datetime math between two floating datetimes and two datetimes with
  2205. time zones are not really comparable.
  2206.  
  2207. If you are planning to use any objects with a real time zone, it is
  2208. strongly recommended that you B<do not> mix these with floating
  2209. datetimes.
  2210.  
  2211. =head2 Math
  2212.  
  2213. If you are going to be using doing date math, please read the section
  2214. L<How Datetime Math is Done>.
  2215.  
  2216. =head2 Time Zone Warnings
  2217.  
  2218. Determining the local time zone for a system can be slow. If C<$ENV{TZ}> is
  2219. not set, it may involve reading a number of files in F</etc> or elsewhere. If
  2220. you know that the local time zone won't change while your code is running, and
  2221. you need to make many objects for the local time zone, it is strongly
  2222. recommended that you retrieve the local time zone once and cache it:
  2223.  
  2224.   our $App::LocalTZ = DateTime::TimeZone->new( name => 'local' );
  2225.  
  2226.   ... # then everywhere else
  2227.  
  2228.   my $dt = DateTime->new( ..., time_zone => $App::LocalTZ );
  2229.  
  2230. DateTime itself does not do this internally because local time zones can
  2231. change, and there's no good way to determine if it's changed without doing all
  2232. the work to look it up.
  2233.  
  2234. Do not try to use named time zones (like "America/Chicago") with dates
  2235. very far in the future (thousands of years). The current
  2236. implementation of C<DateTime::TimeZone> will use a huge amount of
  2237. memory calculating all the DST changes from now until the future
  2238. date. Use UTC or the floating time zone and you will be safe.
  2239.  
  2240. =head2 Methods
  2241.  
  2242. =head3 Constructors
  2243.  
  2244. All constructors can die when invalid parameters are given.
  2245.  
  2246. =over 4
  2247.  
  2248. =item * DateTime->new( ... )
  2249.  
  2250. This class method accepts parameters for each date and time component:
  2251. "year", "month", "day", "hour", "minute", "second", "nanosecond".
  2252. It also accepts "locale", "time_zone", and "formatter" parameters.
  2253.  
  2254.   my $dt = DateTime->new( year   => 1066,
  2255.                           month  => 10,
  2256.                           day    => 25,
  2257.                           hour   => 7,
  2258.                           minute => 15,
  2259.                           second => 47,
  2260.                           nanosecond => 500000000,
  2261.                           time_zone  => 'America/Chicago',
  2262.                         );
  2263.  
  2264. DateTime validates the "month", "day", "hour", "minute", and "second",
  2265. and "nanosecond" parameters.  The valid values for these parameters are:
  2266.  
  2267. =over 8
  2268.  
  2269. =item * month
  2270.  
  2271. An integer from 1-12.
  2272.  
  2273. =item * day
  2274.  
  2275. An integer from 1-31, and it must be within the valid range of days for the
  2276. specified month.
  2277.  
  2278. =item * hour
  2279.  
  2280. An integer from 0-23.
  2281.  
  2282. =item * minute
  2283.  
  2284. An integer from 0-59.
  2285.  
  2286. =item * second
  2287.  
  2288. An integer from 0-61 (to allow for leap seconds).  Values of 60 or 61 are only
  2289. allowed when they match actual leap seconds.
  2290.  
  2291. =item * nanosecond
  2292.  
  2293. An integer >= 0. If this number is greater than 1 billion, it will be
  2294. normalized into the second value for the DateTime object.
  2295.  
  2296. =back
  2297.  
  2298. =back
  2299.  
  2300. Invalid parameter types (like an array reference) will cause the
  2301. constructor to die.
  2302.  
  2303. The value for seconds may be from 0 to 61, to account for leap
  2304. seconds.  If you give a value greater than 59, DateTime does check to
  2305. see that it really matches a valid leap second.
  2306.  
  2307. All of the parameters are optional except for "year".  The "month" and
  2308. "day" parameters both default to 1, while the "hour", "minute",
  2309. "second", and "nanosecond" parameters all default to 0.
  2310.  
  2311. The "locale" parameter should be a string matching one of the valid
  2312. locales, or a C<DateTime::Locale> object.  See the
  2313. L<DateTime::Locale|DateTime::Locale> documentation for details.
  2314.  
  2315. The time_zone parameter can be either a scalar or a
  2316. C<DateTime::TimeZone> object.  A string will simply be passed to the
  2317. C<< DateTime::TimeZone->new >> method as its "name" parameter.  This
  2318. string may be an Olson DB time zone name ("America/Chicago"), an
  2319. offset string ("+0630"), or the words "floating" or "local".  See the
  2320. C<DateTime::TimeZone> documentation for more details.
  2321.  
  2322. The default time zone is "floating".
  2323.  
  2324. The "formatter" can be either a scalar or an object, but the class
  2325. specified by the scalar or the object must implement a
  2326. C<format_datetime()> method.
  2327.  
  2328. =head4 Parsing Dates
  2329.  
  2330. B<This module does not parse dates!> That means there is no
  2331. constructor to which you can pass things like "March 3, 1970 12:34".
  2332.  
  2333. Instead, take a look at the various C<DateTime::Format::*> modules on
  2334. CPAN. These parse all sorts of different date formats, and you're
  2335. bound to find something that can handle your particular needs.
  2336.  
  2337. =head4 Ambiguous Local Times
  2338.  
  2339. Because of Daylight Saving Time, it is possible to specify a local
  2340. time that is ambiguous.  For example, in the US in 2003, the
  2341. transition from to saving to standard time occurred on October 26, at
  2342. 02:00:00 local time.  The local clock changed from 01:59:59 (saving
  2343. time) to 01:00:00 (standard time).  This means that the hour from
  2344. 01:00:00 through 01:59:59 actually occurs twice, though the UTC time
  2345. continues to move forward.
  2346.  
  2347. If you specify an ambiguous time, then the latest UTC time is always
  2348. used, in effect always choosing standard time.  In this case, you can
  2349. simply subtract an hour to the object in order to move to saving time,
  2350. for example:
  2351.  
  2352.   # This object represent 01:30:00 standard time
  2353.   my $dt = DateTime->new( year   => 2003,
  2354.                           month  => 10,
  2355.                           day    => 26,
  2356.                           hour   => 1,
  2357.                           minute => 30,
  2358.                           second => 0,
  2359.                           time_zone => 'America/Chicago',
  2360.                         );
  2361.  
  2362.   print $dt->hms;  # prints 01:30:00
  2363.  
  2364.   # Now the object represent 01:30:00 saving time
  2365.   $dt->subtract( hours => 1 );
  2366.  
  2367.   print $dt->hms;  # still prints 01:30:00
  2368.  
  2369. Alternately, you could create the object with the UTC time zone, and
  2370. then call the C<set_time_zone()> method to change the time zone.  This
  2371. is a good way to ensure that the time is not ambiguous.
  2372.  
  2373. =head4 Invalid Local Times
  2374.  
  2375. Another problem introduced by Daylight Saving Time is that certain
  2376. local times just do not exist.  For example, in the US in 2003, the
  2377. transition from standard to saving time occurred on April 6, at the
  2378. change to 2:00:00 local time.  The local clock changes from 01:59:59
  2379. (standard time) to 03:00:00 (saving time).  This means that there is
  2380. no 02:00:00 through 02:59:59 on April 6!
  2381.  
  2382. Attempting to create an invalid time currently causes a fatal error.
  2383. This may change in future version of this module.
  2384.  
  2385. =over 4
  2386.  
  2387. =item * DateTime->from_epoch( epoch => $epoch, ... )
  2388.  
  2389. This class method can be used to construct a new DateTime object from
  2390. an epoch time instead of components.  Just as with the C<new()>
  2391. method, it accepts "time_zone", "locale", and "formatter" parameters.
  2392.  
  2393. If the epoch value is not an integer, the part after the decimal will
  2394. be converted to nanoseconds.  This is done in order to be compatible
  2395. with C<Time::HiRes>.  If the floating portion extends past 9 decimal
  2396. places, it will be truncated to nine, so that 1.1234567891 will become
  2397. 1 second and 123,456,789 nanoseconds.
  2398.  
  2399. By default, the returned object will be in the UTC time zone.
  2400.  
  2401. =item * DateTime->now( ... )
  2402.  
  2403. This class method is equivalent to calling C<from_epoch()> with the
  2404. value returned from Perl's C<time()> function.  Just as with the
  2405. C<new()> method, it accepts "time_zone" and "locale" parameters.
  2406.  
  2407. By default, the returned object will be in the UTC time zone.
  2408.  
  2409. =item * DateTime->today( ... )
  2410.  
  2411. This class method is equivalent to:
  2412.  
  2413.   DateTime->now->truncate( to => 'day' );
  2414.  
  2415. =item * DateTime->from_object( object => $object, ... )
  2416.  
  2417. This class method can be used to construct a new DateTime object from
  2418. any object that implements the C<utc_rd_values()> method.  All
  2419. C<DateTime::Calendar> modules must implement this method in order to
  2420. provide cross-calendar compatibility.  This method accepts a
  2421. "locale" and "formatter" parameter
  2422.  
  2423. If the object passed to this method has a C<time_zone()> method, that
  2424. is used to set the time zone of the newly created C<DateTime.pm>
  2425. object.
  2426.  
  2427. Otherwise, the returned object will be in the floating time zone.
  2428.  
  2429. =item * DateTime->last_day_of_month( ... )
  2430.  
  2431. This constructor takes the same arguments as can be given to the
  2432. C<new()> method, except for "day".  Additionally, both "year" and
  2433. "month" are required.
  2434.  
  2435. =item * DateTime->from_day_of_year( ... )
  2436.  
  2437. This constructor takes the same arguments as can be given to the
  2438. C<new()> method, except that it does not accept a "month" or "day"
  2439. argument.  Instead, it requires both "year" and "day_of_year".  The
  2440. day of year must be between 1 and 366, and 366 is only allowed for
  2441. leap years.
  2442.  
  2443. =item * $dt->clone()
  2444.  
  2445. This object method returns a new object that is replica of the object
  2446. upon which the method is called.
  2447.  
  2448. =back
  2449.  
  2450. =head3 "Get" Methods
  2451.  
  2452. This class has many methods for retrieving information about an
  2453. object.
  2454.  
  2455. =over 4
  2456.  
  2457. =item * $dt->year()
  2458.  
  2459. Returns the year.
  2460.  
  2461. =item * $dt->ce_year()
  2462.  
  2463. Returns the year according to the BCE/CE numbering system.  The year
  2464. before year 1 in this system is year -1, aka "1 BCE".
  2465.  
  2466. =item * $dt->era_name()
  2467.  
  2468. Returns the long name of the current era, something like "Before
  2469. Christ".  See the L<Locales|/Locales> section for more details.
  2470.  
  2471. =item * $dt->era_abbr()
  2472.  
  2473. Returns the abbreviated name of the current era, something like "BC".
  2474. See the L<Locales|/Locales> section for more details.
  2475.  
  2476. =item * $dt->christian_era()
  2477.  
  2478. Returns a string, either "BC" or "AD", according to the year.
  2479.  
  2480. =item * $dt->secular_era()
  2481.  
  2482. Returns a string, either "BCE" or "CE", according to the year.
  2483.  
  2484. =item * $dt->year_with_era()
  2485.  
  2486. Returns a string containing the year immediately followed by its era
  2487. abbreviation.  The year is the absolute value of C<ce_year()>, so that
  2488. year 1 is "1AD" and year 0 is "1BC".
  2489.  
  2490. =item * $dt->year_with_christian_era()
  2491.  
  2492. Like C<year_with_era()>, but uses the christian_era() to get the era
  2493. name.
  2494.  
  2495. =item * $dt->year_with_secular_era()
  2496.  
  2497. Like C<year_with_era()>, but uses the secular_era() method to get the
  2498. era name.
  2499.  
  2500. =item * $dt->month()
  2501.  
  2502. =item * $dt->mon()
  2503.  
  2504. Returns the month of the year, from 1..12.
  2505.  
  2506. =item * $dt->month_name()
  2507.  
  2508. Returns the name of the current month.  See the
  2509. L<Locales|/Locales> section for more details.
  2510.  
  2511. =item * $dt->month_abbr()
  2512.  
  2513. Returns the abbreviated name of the current month.  See the
  2514. L<Locales|/Locales> section for more details.
  2515.  
  2516. =item * $dt->day_of_month()
  2517.  
  2518. =item * $dt->day()
  2519.  
  2520. =item * $dt->mday()
  2521.  
  2522. Returns the day of the month, from 1..31.
  2523.  
  2524. =item * $dt->day_of_week()
  2525.  
  2526. =item * $dt->wday()
  2527.  
  2528. =item * $dt->dow()
  2529.  
  2530. Returns the day of the week as a number, from 1..7, with 1 being
  2531. Monday and 7 being Sunday.
  2532.  
  2533. =item * $dt->local_day_of_week()
  2534.  
  2535. Returns the day of the week as a number, from 1..7. The day
  2536. corresponding to 1 will vary based on the locale.
  2537.  
  2538. =item * $dt->day_name()
  2539.  
  2540. Returns the name of the current day of the week.  See the
  2541. L<Locales|/Locales> section for more details.
  2542.  
  2543. =item * $dt->day_abbr()
  2544.  
  2545. Returns the abbreviated name of the current day of the week.  See the
  2546. L<Locales|/Locales> section for more details.
  2547.  
  2548. =item * $dt->day_of_year()
  2549.  
  2550. =item * $dt->doy()
  2551.  
  2552. Returns the day of the year.
  2553.  
  2554. =item * $dt->quarter()
  2555.  
  2556. Returns the quarter of the year, from 1..4.
  2557.  
  2558. =item * $dt->quarter_name()
  2559.  
  2560. Returns the name of the current quarter.  See the
  2561. L<Locales|/Locales> section for more details.
  2562.  
  2563. =item * $dt->quarter_abbr()
  2564.  
  2565. Returns the abbreviated name of the current quarter.  See the
  2566. L<Locales|/Locales> section for more details.
  2567.  
  2568. =item * $dt->day_of_quarter()
  2569.  
  2570. =item * $dt->doq()
  2571.  
  2572. Returns the day of the quarter.
  2573.  
  2574. =item * $dt->weekday_of_month()
  2575.  
  2576. Returns a number from 1..5 indicating which week day of the month this
  2577. is.  For example, June 9, 2003 is the second Monday of the month, and
  2578. so this method returns 2 for that day.
  2579.  
  2580. =item * $dt->ymd( $optional_separator ) - also $dt->date(...)
  2581.  
  2582. =item * $dt->mdy( $optional_separator )
  2583.  
  2584. =item * $dt->dmy( $optional_separator )
  2585.  
  2586. Each method returns the year, month, and day, in the order indicated
  2587. by the method name.  Years are zero-padded to four digits.  Months and
  2588. days are 0-padded to two digits.
  2589.  
  2590. By default, the values are separated by a dash (-), but this can be
  2591. overridden by passing a value to the method.
  2592.  
  2593. =item * $dt->hour()
  2594.  
  2595. Returns the hour of the day, from 0..23.
  2596.  
  2597. =item * $dt->hour_1()
  2598.  
  2599. Returns the hour of the day, from 1..24.
  2600.  
  2601. =item * $dt->hour_12()
  2602.  
  2603. Returns the hour of the day, from 1..12.
  2604.  
  2605. =item * $dt->hour_12_0()
  2606.  
  2607. Returns the hour of the day, from 0..11.
  2608.  
  2609. =item * $dt->am_or_pm()
  2610.  
  2611. Returns the appropriate localized abbreviation, depending on the
  2612. current hour.
  2613.  
  2614. =item * $dt->minute()
  2615.  
  2616. =item * $dt->min()
  2617.  
  2618. Returns the minute of the hour, from 0..59.
  2619.  
  2620. =item * $dt->second()
  2621.  
  2622. =item * $dt->sec()
  2623.  
  2624. Returns the second, from 0..61.  The values 60 and 61 are used for
  2625. leap seconds.
  2626.  
  2627. =item * $dt->fractional_second()
  2628.  
  2629. Returns the second, as a real number from 0.0 until 61.999999999
  2630.  
  2631. The values 60 and 61 are used for leap seconds.
  2632.  
  2633. =item * $dt->millisecond()
  2634.  
  2635. Returns the fractional part of the second as milliseconds (1E-3 seconds).
  2636.  
  2637. Half a second is 500 milliseconds.
  2638.  
  2639. =item * $dt->microsecond()
  2640.  
  2641. Returns the fractional part of the second as microseconds (1E-6
  2642. seconds).  This value will be rounded to an integer.
  2643.  
  2644. Half a second is 500_000 microseconds.  This value will be rounded to
  2645. an integer.
  2646.  
  2647. =item * $dt->nanosecond()
  2648.  
  2649. Returns the fractional part of the second as nanoseconds (1E-9 seconds).
  2650.  
  2651. Half a second is 500_000_000 nanoseconds.
  2652.  
  2653. =item * $dt->hms( $optional_separator )
  2654.  
  2655. =item * $dt->time( $optional_separator )
  2656.  
  2657. Returns the hour, minute, and second, all zero-padded to two digits.
  2658. If no separator is specified, a colon (:) is used by default.
  2659.  
  2660. =item * $dt->datetime()
  2661.  
  2662. =item * $dt->iso8601()
  2663.  
  2664. This method is equivalent to:
  2665.  
  2666.   $dt->ymd('-') . 'T' . $dt->hms(':')
  2667.  
  2668. =item * $dt->is_leap_year()
  2669.  
  2670. This method returns a true or false indicating whether or not the
  2671. datetime object is in a leap year.
  2672.  
  2673. =item * $dt->week()
  2674.  
  2675.  ($week_year, $week_number) = $dt->week;
  2676.  
  2677. Returns information about the calendar week which contains this
  2678. datetime object. The values returned by this method are also available
  2679. separately through the week_year and week_number methods.
  2680.  
  2681. The first week of the year is defined by ISO as the one which contains
  2682. the fourth day of January, which is equivalent to saying that it's the
  2683. first week to overlap the new year by at least four days.
  2684.  
  2685. Typically the week year will be the same as the year that the object
  2686. is in, but dates at the very beginning of a calendar year often end up
  2687. in the last week of the prior year, and similarly, the final few days
  2688. of the year may be placed in the first week of the next year.
  2689.  
  2690. =item * $dt->week_year()
  2691.  
  2692. Returns the year of the week. See C<< $dt->week() >> for details.
  2693.  
  2694. =item * $dt->week_number()
  2695.  
  2696. Returns the week of the year, from 1..53. See C<< $dt->week() >> for details.
  2697.  
  2698. =item * $dt->week_of_month()
  2699.  
  2700. The week of the month, from 0..5.  The first week of the month is the
  2701. first week that contains a Thursday.  This is based on the ICU
  2702. definition of week of month, and correlates to the ISO8601 week of
  2703. year definition.  A day in the week I<before> the week with the first
  2704. Thursday will be week 0.
  2705.  
  2706. =item * $dt->jd()
  2707.  
  2708. =item * $dt->mjd()
  2709.  
  2710. These return the Julian Day and Modified Julian Day, respectively.
  2711. The value returned is a floating point number.  The fractional portion
  2712. of the number represents the time portion of the datetime.
  2713.  
  2714. =item * $dt->time_zone()
  2715.  
  2716. This returns the C<DateTime::TimeZone> object for the datetime object.
  2717.  
  2718. =item * $dt->offset()
  2719.  
  2720. This returns the offset from UTC, in seconds, of the datetime object
  2721. according to the time zone.
  2722.  
  2723. =item * $dt->is_dst()
  2724.  
  2725. Returns a boolean indicating whether or not the datetime object is
  2726. currently in Daylight Saving Time or not.
  2727.  
  2728. =item * $dt->time_zone_long_name()
  2729.  
  2730. This is a shortcut for C<< $dt->time_zone->name >>.  It's provided so
  2731. that one can use "%{time_zone_long_name}" as a strftime format
  2732. specifier.
  2733.  
  2734. =item * $dt->time_zone_short_name()
  2735.  
  2736. This method returns the time zone abbreviation for the current time
  2737. zone, such as "PST" or "GMT".  These names are B<not> definitive, and
  2738. should not be used in any application intended for general use by
  2739. users around the world.
  2740.  
  2741. =item * $dt->strftime( $format, ... )
  2742.  
  2743. This method implements functionality similar to the C<strftime()>
  2744. method in C.  However, if given multiple format strings, then it will
  2745. return multiple scalars, one for each format string.
  2746.  
  2747. See the L<strftime Patterns> section for a list of all possible
  2748. strftime patterns.
  2749.  
  2750. If you give a pattern that doesn't exist, then it is simply treated as
  2751. text.
  2752.  
  2753. =item * $dt->format_cldr( $format, ... )
  2754.  
  2755. This method implements formatting based on the CLDR date patterns.  If
  2756. given multiple format strings, then it will return multiple scalars,
  2757. one for each format string.
  2758.  
  2759. See the L<CLDR Patterns> section for a list of all possible CLDR
  2760. patterns.
  2761.  
  2762. If you give a pattern that doesn't exist, then it is simply treated as
  2763. text.
  2764.  
  2765. =item * $dt->epoch()
  2766.  
  2767. Return the UTC epoch value for the datetime object.  Internally, this
  2768. is implemented using C<Time::Local>, which uses the Unix epoch even on
  2769. machines with a different epoch (such as MacOS).  Datetimes before the
  2770. start of the epoch will be returned as a negative number.
  2771.  
  2772. The return value from this method is always an integer.
  2773.  
  2774. Since the epoch does not account for leap seconds, the epoch time for
  2775. 1972-12-31T23:59:60 (UTC) is exactly the same as that for
  2776. 1973-01-01T00:00:00.
  2777.  
  2778. This module uses C<Time::Local> to calculate the epoch, which may or
  2779. may not handle epochs before 1904 or after 2038 (depending on the size
  2780. of your system's integers, and whether or not Perl was compiled with
  2781. 64-bit int support).
  2782.  
  2783. =item * $dt->hires_epoch()
  2784.  
  2785. Returns the epoch as a floating point number.  The floating point
  2786. portion of the value represents the nanosecond value of the object.
  2787. This method is provided for compatibility with the C<Time::HiRes>
  2788. module.
  2789.  
  2790. =item * $dt->is_finite()
  2791.  
  2792. =item * $dt->is_infinite
  2793.  
  2794. These methods allow you to distinguish normal datetime objects from
  2795. infinite ones.  Infinite datetime objects are documented in
  2796. L<DateTime::Infinite|DateTime::Infinite>.
  2797.  
  2798. =item * $dt->utc_rd_values()
  2799.  
  2800. Returns the current UTC Rata Die days, seconds, and nanoseconds as a
  2801. three element list.  This exists primarily to allow other calendar
  2802. modules to create objects based on the values provided by this object.
  2803.  
  2804. =item * $dt->local_rd_values()
  2805.  
  2806. Returns the current local Rata Die days, seconds, and nanoseconds as a
  2807. three element list.  This exists for the benefit of other modules
  2808. which might want to use this information for date math, such as
  2809. C<DateTime::Event::Recurrence>.
  2810.  
  2811. =item * $dt->leap_seconds()
  2812.  
  2813. Returns the number of leap seconds that have happened up to the
  2814. datetime represented by the object.  For floating datetimes, this
  2815. always returns 0.
  2816.  
  2817. =item * $dt->utc_rd_as_seconds()
  2818.  
  2819. Returns the current UTC Rata Die days and seconds purely as seconds.
  2820. This number ignores any fractional seconds stored in the object,
  2821. as well as leap seconds.
  2822.  
  2823. =item * $dt->local_rd_as_seconds() - deprecated
  2824.  
  2825. Returns the current local Rata Die days and seconds purely as seconds.
  2826. This number ignores any fractional seconds stored in the object,
  2827. as well as leap seconds.
  2828.  
  2829. =item * $dt->locale()
  2830.  
  2831. Returns the current locale object.
  2832.  
  2833. =item * $dt->formatter()
  2834.  
  2835. Returns current formatter object or class. See L<Formatters And
  2836. Stringification> for details.
  2837.  
  2838. =back
  2839.  
  2840. =head3 "Set" Methods
  2841.  
  2842. The remaining methods provided by C<DateTime.pm>, except where otherwise
  2843. specified, return the object itself, thus making method chaining
  2844. possible. For example:
  2845.  
  2846.   my $dt = DateTime->now->set_time_zone( 'Australia/Sydney' );
  2847.  
  2848.   my $first = DateTime
  2849.                 ->last_day_of_month( year => 2003, month => 3 )
  2850.                 ->add( days => 1 )
  2851.                 ->subtract( seconds => 1 );
  2852.  
  2853. =over 4
  2854.  
  2855. =item * $dt->set( .. )
  2856.  
  2857. This method can be used to change the local components of a date time,
  2858. or its locale.  This method accepts any parameter allowed by the
  2859. C<new()> method except for "time_zone".  Time zones may be set using
  2860. the C<set_time_zone()> method.
  2861.  
  2862. This method performs parameters validation just as is done in the
  2863. C<new()> method.
  2864.  
  2865. =item * $dt->set_year()
  2866.  
  2867. =item * $dt->set_month()
  2868.  
  2869. =item * $dt->set_day()
  2870.  
  2871. =item * $dt->set_hour()
  2872.  
  2873. =item * $dt->set_minute()
  2874.  
  2875. =item * $dt->set_second()
  2876.  
  2877. =item * $dt->set_nanosecond()
  2878.  
  2879. =item * $dt->set_locale()
  2880.  
  2881. These are shortcuts to calling C<set()> with a single key.  They all
  2882. take a single parameter.
  2883.  
  2884. =item * $dt->truncate( to => ... )
  2885.  
  2886. This method allows you to reset some of the local time components in
  2887. the object to their "zero" values.  The "to" parameter is used to
  2888. specify which values to truncate, and it may be one of "year",
  2889. "month", "week", "day", "hour", "minute", or "second".  For example,
  2890. if "month" is specified, then the local day becomes 1, and the hour,
  2891. minute, and second all become 0.
  2892.  
  2893. If "week" is given, then the datetime is set to the beginning of the
  2894. week in which it occurs, and the time components are all set to 0.
  2895.  
  2896. =item * $dt->set_time_zone( $tz )
  2897.  
  2898. This method accepts either a time zone object or a string that can be
  2899. passed as the "name" parameter to C<< DateTime::TimeZone->new() >>.
  2900. If the new time zone's offset is different from the old time zone,
  2901. then the I<local> time is adjusted accordingly.
  2902.  
  2903. For example:
  2904.  
  2905.   my $dt = DateTime->new( year => 2000, month => 5, day => 10,
  2906.                           hour => 15, minute => 15,
  2907.                           time_zone => 'America/Los_Angeles', );
  2908.  
  2909.   print $dt->hour; # prints 15
  2910.  
  2911.   $dt->set_time_zone( 'America/Chicago' );
  2912.  
  2913.   print $dt->hour; # prints 17
  2914.  
  2915. If the old time zone was a floating time zone, then no adjustments to
  2916. the local time are made, except to account for leap seconds.  If the
  2917. new time zone is floating, then the I<UTC> time is adjusted in order
  2918. to leave the local time untouched.
  2919.  
  2920. Fans of Tsai Ming-Liang's films will be happy to know that this does
  2921. work:
  2922.  
  2923.   my $dt = DateTime->now( time_zone => 'Asia/Taipei' );
  2924.  
  2925.   $dt->set_time_zone( 'Europe/Paris' );
  2926.  
  2927. Yes, now we can know "ni3 na4 bian1 ji2dian3?"
  2928.  
  2929. =item * $dt->set_formatter( $formatter )
  2930.  
  2931. Set the formatter for the object. See L<Formatters And
  2932. Stringification> for details.
  2933.  
  2934. You can set this to C<undef> to revert to the default formatter.
  2935.  
  2936. =back
  2937.  
  2938. =head3 Math Methods
  2939.  
  2940. Like the set methods, math related methods always return the object
  2941. itself, to allow for chaining:
  2942.  
  2943.   $dt->add( days => 1 )->subtract( seconds => 1 );
  2944.  
  2945. =over 4
  2946.  
  2947. =item * $dt->duration_class()
  2948.  
  2949. This returns C<DateTime::Duration>, but exists so that a subclass of
  2950. C<DateTime.pm> can provide a different value.
  2951.  
  2952. =item * $dt->add_duration( $duration_object )
  2953.  
  2954. This method adds a C<DateTime::Duration> to the current datetime.  See
  2955. the L<DateTime::Duration|DateTime::Duration> docs for more details.
  2956.  
  2957. =item * $dt->add( DateTime::Duration->new parameters )
  2958.  
  2959. This method is syntactic sugar around the C<add_duration()> method.  It
  2960. simply creates a new C<DateTime::Duration> object using the parameters
  2961. given, and then calls the C<add_duration()> method.
  2962.  
  2963. =item * $dt->subtract_duration( $duration_object )
  2964.  
  2965. When given a C<DateTime::Duration> object, this method simply calls
  2966. C<invert()> on that object and passes that new duration to the
  2967. C<add_duration> method.
  2968.  
  2969. =item * $dt->subtract( DateTime::Duration->new parameters )
  2970.  
  2971. Like C<add()>, this is syntactic sugar for the C<subtract_duration()>
  2972. method.
  2973.  
  2974. =item * $dt->subtract_datetime( $datetime )
  2975.  
  2976. This method returns a new C<DateTime::Duration> object representing
  2977. the difference between the two dates.  The duration is B<relative> to
  2978. the object from which C<$datetime> is subtracted.  For example:
  2979.  
  2980.     2003-03-15 00:00:00.00000000
  2981.  -  2003-02-15 00:00:00.00000000
  2982.  
  2983.  -------------------------------
  2984.  
  2985.  = 1 month
  2986.  
  2987. Note that this duration is not an absolute measure of the amount of
  2988. time between the two datetimes, because the length of a month varies,
  2989. as well as due to the presence of leap seconds.
  2990.  
  2991. The returned duration may have deltas for months, days, minutes,
  2992. seconds, and nanoseconds.
  2993.  
  2994. =item * $dt->delta_md( $datetime )
  2995.  
  2996. =item * $dt->delta_days( $datetime )
  2997.  
  2998. Each of these methods returns a new C<DateTime::Duration> object
  2999. representing some portion of the difference between two datetimes.
  3000. The C<delta_md()> method returns a duration which contains only the
  3001. month and day portions of the duration is represented.  The
  3002. C<delta_days()> method returns a duration which contains only days.
  3003.  
  3004. The C<delta_md> and C<delta_days> methods truncate the duration so
  3005. that any fractional portion of a day is ignored.  Both of these
  3006. methods operate on the date portion of a datetime only, and so
  3007. effectively ignore the time zone.
  3008.  
  3009. Unlike the subtraction methods, B<these methods always return a
  3010. positive (or zero) duration>.
  3011.  
  3012. =item * $dt->delta_ms( $datetime )
  3013.  
  3014. Returns a duration which contains only minutes and seconds.  Any day
  3015. and month differences to minutes are converted to minutes and
  3016. seconds. This method also B<always return a positive (or zero)
  3017. duration>.
  3018.  
  3019. =item * $dt->subtract_datetime_absolute( $datetime )
  3020.  
  3021. This method returns a new C<DateTime::Duration> object representing
  3022. the difference between the two dates in seconds and nanoseconds.  This
  3023. is the only way to accurately measure the absolute amount of time
  3024. between two datetimes, since units larger than a second do not
  3025. represent a fixed number of seconds.
  3026.  
  3027. =back
  3028.  
  3029. =head3 Class Methods
  3030.  
  3031. =over 4
  3032.  
  3033. =item * DateTime->DefaultLocale( $locale )
  3034.  
  3035. This can be used to specify the default locale to be used when
  3036. creating DateTime objects.  If unset, then "en_US" is used.
  3037.  
  3038. =item * DateTime->compare( $dt1, $dt2 )
  3039.  
  3040. =item * DateTime->compare_ignore_floating( $dt1, $dt2 )
  3041.  
  3042.   $cmp = DateTime->compare( $dt1, $dt2 );
  3043.  
  3044.   $cmp = DateTime->compare_ignore_floating( $dt1, $dt2 );
  3045.  
  3046. Compare two DateTime objects.  The semantics are compatible with Perl's
  3047. C<sort()> function; it returns -1 if $dt1 < $dt2, 0 if $dt1 == $dt2, 1 if $dt1
  3048. > $dt2.
  3049.  
  3050. If one of the two DateTime objects has a floating time zone, it will
  3051. first be converted to the time zone of the other object.  This is what
  3052. you want most of the time, but it can lead to inconsistent results
  3053. when you compare a number of DateTime objects, some of which are
  3054. floating, and some of which are in other time zones.
  3055.  
  3056. If you want to have consistent results (because you want to sort a
  3057. number of objects, for example), you can use the
  3058. C<compare_ignore_floating()> method:
  3059.  
  3060.   @dates = sort { DateTime->compare_ignore_floating($a, $b) } @dates;
  3061.  
  3062. In this case, objects with a floating time zone will be sorted as if
  3063. they were UTC times.
  3064.  
  3065. Since DateTime objects overload comparison operators, this:
  3066.  
  3067.   @dates = sort @dates;
  3068.  
  3069. is equivalent to this:
  3070.  
  3071.   @dates = sort { DateTime->compare($a, $b) } @dates;
  3072.  
  3073. DateTime objects can be compared to any other calendar class that
  3074. implements the C<utc_rd_values()> method.
  3075.  
  3076. =back
  3077.  
  3078. =head2 How Datetime Math is Done
  3079.  
  3080. It's important to have some understanding of how datetime math is
  3081. implemented in order to effectively use this module and
  3082. C<DateTime::Duration>.
  3083.  
  3084. =head3 Making Things Simple
  3085.  
  3086. If you want to simplify your life and not have to think too hard about
  3087. the nitty-gritty of datetime math, I have several recommendations:
  3088.  
  3089. =over 4
  3090.  
  3091. =item * use the floating time zone
  3092.  
  3093. If you do not care about time zones or leap seconds, use the
  3094. "floating" timezone:
  3095.  
  3096.   my $dt = DateTime->now( time_zone => 'floating' );
  3097.  
  3098. Math done on two objects in the floating time zone produces very
  3099. predictable results.
  3100.  
  3101. Note that in most cases you will want to start by creating an object in a
  3102. specific zone and I<then> convert it to the floating time zone. When an object
  3103. goes from a real zone to the floating zone, the time for the object remains
  3104. the same.
  3105.  
  3106. This means that passing the floating zone to a constructor may not do what you
  3107. want.
  3108.  
  3109.   my $dt = DateTime->now( time_zone => 'floating' );
  3110.  
  3111. is equivalent to
  3112.  
  3113.   my $dt = DateTime->now( time_zone => 'UTC' )->set_time_zone('floating');
  3114.  
  3115. This might not be what you wanted. Instead, you may prefer to do this:
  3116.  
  3117.   my $dt = DateTime->now( time_zone => 'local' )->set_time_zone('floating');
  3118.  
  3119. =item * use UTC for all calculations
  3120.  
  3121. If you do care about time zones (particularly DST) or leap seconds,
  3122. try to use non-UTC time zones for presentation and user input only.
  3123. Convert to UTC immediately and convert back to the local time zone for
  3124. presentation:
  3125.  
  3126.   my $dt = DateTime->new( %user_input, time_zone => $user_tz );
  3127.   $dt->set_time_zone('UTC');
  3128.  
  3129.   # do various operations - store it, retrieve it, add, subtract, etc.
  3130.  
  3131.   $dt->set_time_zone($user_tz);
  3132.   print $dt->datetime;
  3133.  
  3134. =item * math on non-UTC time zones
  3135.  
  3136. If you need to do date math on objects with non-UTC time zones, please
  3137. read the caveats below carefully.  The results C<DateTime.pm> produces are
  3138. predictable and correct, and mostly intuitive, but datetime math gets
  3139. very ugly when time zones are involved, and there are a few strange
  3140. corner cases involving subtraction of two datetimes across a DST
  3141. change.
  3142.  
  3143. If you can always use the floating or UTC time zones, you can skip
  3144. ahead to L<Leap Seconds and Date Math|Leap Seconds and Date Math>
  3145.  
  3146. =item * date vs datetime math
  3147.  
  3148. If you only care about the date (calendar) portion of a datetime, you
  3149. should use either C<delta_md()> or C<delta_days()>, not
  3150. C<subtract_datetime()>.  This will give predictable, unsurprising
  3151. results, free from DST-related complications.
  3152.  
  3153. =item * subtract_datetime() and add_duration()
  3154.  
  3155. You must convert your datetime objects to the UTC time zone before
  3156. doing date math if you want to make sure that the following formulas
  3157. are always true:
  3158.  
  3159.   $dt2 - $dt1 = $dur
  3160.   $dt1 + $dur = $dt2
  3161.   $dt2 - $dur = $dt1
  3162.  
  3163. Note that using C<delta_days> ensures that this formula always works,
  3164. regardless of the timezone of the objects involved, as does using
  3165. C<subtract_datetime_absolute()>. Other methods of subtraction are not
  3166. always reversible.
  3167.  
  3168. =back
  3169.  
  3170. =head3 Adding a Duration to a Datetime
  3171.  
  3172. The parts of a duration can be broken down into five parts.  These are
  3173. months, days, minutes, seconds, and nanoseconds.  Adding one month to
  3174. a date is different than adding 4 weeks or 28, 29, 30, or 31 days.
  3175. Similarly, due to DST and leap seconds, adding a day can be different
  3176. than adding 86,400 seconds, and adding a minute is not exactly the
  3177. same as 60 seconds.
  3178.  
  3179. We cannot convert between these units, except for seconds and
  3180. nanoseconds, because there is no fixed conversion between the two
  3181. units, because of things like leap seconds, DST changes, etc.
  3182.  
  3183. C<DateTime.pm> always adds (or subtracts) days, then months, minutes, and then
  3184. seconds and nanoseconds.  If there are any boundary overflows, these are
  3185. normalized at each step.  For the days and months the local (not UTC) values
  3186. are used.  For minutes and seconds, the local values are used.  This generally
  3187. just works.
  3188.  
  3189. This means that adding one month and one day to February 28, 2003 will
  3190. produce the date April 1, 2003, not March 29, 2003.
  3191.  
  3192.   my $dt = DateTime->new( year => 2003, month => 2, day => 28 );
  3193.  
  3194.   $dt->add( months => 1, days => 1 );
  3195.  
  3196.   # 2003-04-01 - the result
  3197.  
  3198. On the other hand, if we add months first, and then separately add
  3199. days, we end up with March 29, 2003:
  3200.  
  3201.   $dt->add( months => 1 )->add( days => 1 );
  3202.  
  3203.   # 2003-03-29
  3204.  
  3205. We see similar strangeness when math crosses a DST boundary:
  3206.  
  3207.   my $dt = DateTime->new( year => 2003, month => 4, day => 5,
  3208.                           hour => 1, minute => 58,
  3209.                           time_zone => "America/Chicago",
  3210.                         );
  3211.  
  3212.   $dt->add( days => 1, minutes => 3 );
  3213.   # 2003-04-06 02:01:00
  3214.  
  3215.   $dt->add( minutes => 3 )->add( days => 1 );
  3216.   # 2003-04-06 03:01:00
  3217.  
  3218. Note that if you converted the datetime object to UTC first you would
  3219. get predictable results.
  3220.  
  3221. If you want to know how many seconds a duration object represents, you
  3222. have to add it to a datetime to find out, so you could do:
  3223.  
  3224.  my $now = DateTime->now( time_zone => 'UTC' );
  3225.  my $later = $now->clone->add_duration($duration);
  3226.  
  3227.  my $seconds_dur = $later->subtract_datetime_absolute($now);
  3228.  
  3229. This returns a duration which only contains seconds and nanoseconds.
  3230.  
  3231. If we were add the duration to a different datetime object we might
  3232. get a different number of seconds.
  3233.  
  3234. L<DateTime::Duration> supports three different end-of-month algorithms for
  3235. adding months. This comes into play when an addition results in a day past the
  3236. end of the month (for example, adding one month to January 30).
  3237.  
  3238.  # 2010-08-31 + 1 month = 2010-10-01
  3239.  $dt->add( months => 1, end_of_month => 'wrap' );
  3240.  
  3241.  # 2010-01-30 + 1 month = 2010-02-28
  3242.  $dt->add( months => 1, end_of_month => 'limit' );
  3243.  
  3244.  # 2010-04-30 + 1 month = 2010-05-31
  3245.  $dt->add( months => 1, end_of_month => 'preserve' );
  3246.  
  3247. By default, it uses "wrap" for positive durations and "preserve" for negative
  3248. durations. See L<DateTime::Duration> for a detailed explanation of these
  3249. algorithms.
  3250.  
  3251. If you need to do lots of work with durations, take a look at Rick
  3252. Measham's C<DateTime::Format::Duration> module, which lets you present
  3253. information from durations in many useful ways.
  3254.  
  3255. There are other subtract/delta methods in DateTime.pm to generate
  3256. different types of durations.  These methods are
  3257. C<subtract_datetime()>, C<subtract_datetime_absolute()>,
  3258. C<delta_md()>, C<delta_days()>, and C<delta_ms()>.
  3259.  
  3260. =head3 Datetime Subtraction
  3261.  
  3262. Date subtraction is done solely based on the two object's local
  3263. datetimes, with one exception to handle DST changes.  Also, if the two
  3264. datetime objects are in different time zones, one of them is converted
  3265. to the other's time zone first before subtraction.  This is best
  3266. explained through examples:
  3267.  
  3268. The first of these probably makes the most sense:
  3269.  
  3270.     my $dt1 = DateTime->new( year => 2003, month => 5, day => 6,
  3271.                              time_zone => 'America/Chicago',
  3272.                            );
  3273.     # not DST
  3274.  
  3275.     my $dt2 = DateTime->new( year => 2003, month => 11, day => 6,
  3276.                              time_zone => 'America/Chicago',
  3277.                            );
  3278.     # is DST
  3279.  
  3280.     my $dur = $dt2->subtract_datetime($dt1);
  3281.     # 6 months
  3282.  
  3283. Nice and simple.
  3284.  
  3285. This one is a little trickier, but still fairly logical:
  3286.  
  3287.     my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
  3288.                              hour => 1, minute => 58,
  3289.                              time_zone => "America/Chicago",
  3290.                            );
  3291.     # is DST
  3292.  
  3293.     my $dt2 = DateTime->new( year => 2003, month => 4, day => 7,
  3294.                              hour => 2, minute => 1,
  3295.                              time_zone => "America/Chicago",
  3296.                            );
  3297.     # not DST
  3298.  
  3299.     my $dur = $dt2->subtract_datetime($dt1);
  3300.     # 2 days and 3 minutes
  3301.  
  3302. Which contradicts the result this one gives, even though they both
  3303. make sense:
  3304.  
  3305.     my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
  3306.                              hour => 1, minute => 58,
  3307.                              time_zone => "America/Chicago",
  3308.                            );
  3309.     # is DST
  3310.  
  3311.     my $dt2 = DateTime->new( year => 2003, month => 4, day => 6,
  3312.                              hour => 3, minute => 1,
  3313.                              time_zone => "America/Chicago",
  3314.                            );
  3315.     # not DST
  3316.  
  3317.     my $dur = $dt2->subtract_datetime($dt1);
  3318.     # 1 day and 3 minutes
  3319.  
  3320. This last example illustrates the "DST" exception mentioned earlier.
  3321. The exception accounts for the fact 2003-04-06 only lasts 23 hours.
  3322.  
  3323. And finally:
  3324.  
  3325.     my $dt2 = DateTime->new( year => 2003, month => 10, day => 26,
  3326.                              hour => 1,
  3327.                              time_zone => 'America/Chicago',
  3328.                            );
  3329.  
  3330.     my $dt1 = $dt2->clone->subtract( hours => 1 );
  3331.  
  3332.     my $dur = $dt2->subtract_datetime($dt1);
  3333.     # 60 minutes
  3334.  
  3335. This seems obvious until you realize that subtracting 60 minutes from
  3336. C<$dt2> in the above example still leaves the clock time at
  3337. "01:00:00".  This time we are accounting for a 25 hour day.
  3338.  
  3339. =head3 Reversibility
  3340.  
  3341. Date math operations are not always reversible.  This is because of
  3342. the way that addition operations are ordered.  As was discussed
  3343. earlier, adding 1 day and 3 minutes in one call to C<add()> is not the
  3344. same as first adding 3 minutes and 1 day in two separate calls.
  3345.  
  3346. If we take a duration returned from C<subtract_datetime()> and then
  3347. try to add or subtract that duration from one of the datetimes we just
  3348. used, we sometimes get interesting results:
  3349.  
  3350.   my $dt1 = DateTime->new( year => 2003, month => 4, day => 5,
  3351.                            hour => 1, minute => 58,
  3352.                            time_zone => "America/Chicago",
  3353.                          );
  3354.  
  3355.   my $dt2 = DateTime->new( year => 2003, month => 4, day => 6,
  3356.                            hour => 3, minute => 1,
  3357.                            time_zone => "America/Chicago",
  3358.                          );
  3359.  
  3360.   my $dur = $dt2->subtract_datetime($dt1);
  3361.   # 1 day and 3 minutes
  3362.  
  3363.   $dt1->add_duration($dur);
  3364.   # gives us $dt2
  3365.  
  3366.   $dt2->subtract_duration($dur);
  3367.   # gives us 2003-04-05 02:58:00 - 1 hour later than $dt1
  3368.  
  3369. The C<subtract_dauration()> operation gives us a (perhaps) unexpected
  3370. answer because it first subtracts one day to get 2003-04-05T03:01:00
  3371. and then subtracts 3 minutes to get the final result.
  3372.  
  3373. If we explicitly reverse the order we can get the original value of
  3374. C<$dt1>. This can be facilitated by C<DateTime::Duration>'s
  3375. C<calendar_duration()> and C<clock_duration()> methods:
  3376.  
  3377.   $dt2->subtract_duration( $dur->clock_duration )
  3378.       ->subtract_duration( $dur->calendar_duration );
  3379.  
  3380. =head3 Leap Seconds and Date Math
  3381.  
  3382. The presence of leap seconds can cause even more anomalies in date
  3383. math.  For example, the following is a legal datetime:
  3384.  
  3385.   my $dt = DateTime->new( year => 1972, month => 12, day => 31,
  3386.                           hour => 23, minute => 59, second => 60,
  3387.                           time_zone => 'UTC' );
  3388.  
  3389. If we do the following:
  3390.  
  3391.  $dt->add( months => 1 );
  3392.  
  3393. Then the datetime is now "1973-02-01 00:00:00", because there is no
  3394. 23:59:60 on 1973-01-31.
  3395.  
  3396. Leap seconds also force us to distinguish between minutes and seconds
  3397. during date math.  Given the following datetime:
  3398.  
  3399.   my $dt = DateTime->new( year => 1972, month => 12, day => 31,
  3400.                           hour => 23, minute => 59, second => 30,
  3401.                           time_zone => 'UTC' );
  3402.  
  3403. we will get different results when adding 1 minute than we get if we
  3404. add 60 seconds.  This is because in this case, the last minute of the
  3405. day, beginning at 23:59:00, actually contains 61 seconds.
  3406.  
  3407. Here are the results we get:
  3408.  
  3409.   # 1972-12-31 23:59:30 - our starting datetime
  3410.  
  3411.   $dt->clone->add( minutes => 1 );
  3412.   # 1973-01-01 00:00:30 - one minute later
  3413.  
  3414.   $dt->clone->add( seconds => 60 );
  3415.   # 1973-01-01 00:00:29 - 60 seconds later
  3416.  
  3417.   $dt->clone->add( seconds => 61 );
  3418.   # 1973-01-01 00:00:30 - 61 seconds later
  3419.  
  3420. =head3 Local vs. UTC and 24 hours vs. 1 day
  3421.  
  3422. When math crosses a daylight saving boundary, a single day may have
  3423. more or less than 24 hours.
  3424.  
  3425. For example, if you do this:
  3426.  
  3427.   my $dt = DateTime->new( year => 2003, month => 4, day => 5,
  3428.                           hour => 2,
  3429.                           time_zone => 'America/Chicago',
  3430.                         );
  3431.   $dt->add( days => 1 );
  3432.  
  3433. then you will produce an I<invalid> local time, and therefore an
  3434. exception will be thrown.
  3435.  
  3436. However, this works:
  3437.  
  3438.   my $dt = DateTime->new( year => 2003, month => 4, day => 5,
  3439.                           hour => 2,
  3440.                           time_zone => 'America/Chicago',
  3441.                         );
  3442.   $dt->add( hours => 24 );
  3443.  
  3444. and produces a datetime with the local time of "03:00".
  3445.  
  3446. If all this makes your head hurt, there is a simple alternative.  Just
  3447. convert your datetime object to the "UTC" time zone before doing date
  3448. math on it, and switch it back to the local time zone afterwards.
  3449. This avoids the possibility of having date math throw an exception,
  3450. and makes sure that 1 day equals 24 hours.  Of course, this may not
  3451. always be desirable, so caveat user!
  3452.  
  3453. =head2 Overloading
  3454.  
  3455. This module explicitly overloads the addition (+), subtraction (-),
  3456. string and numeric comparison operators.  This means that the
  3457. following all do sensible things:
  3458.  
  3459.   my $new_dt = $dt + $duration_obj;
  3460.  
  3461.   my $new_dt = $dt - $duration_obj;
  3462.  
  3463.   my $duration_obj = $dt - $new_dt;
  3464.  
  3465.   foreach my $dt ( sort @dts ) { ... }
  3466.  
  3467. Additionally, the fallback parameter is set to true, so other
  3468. derivable operators (+=, -=, etc.) will work properly.  Do not expect
  3469. increment (++) or decrement (--) to do anything useful.
  3470.  
  3471. The string comparison operators, C<eq> or C<ne>, will use the string
  3472. value to compare with non-DateTime objects.
  3473.  
  3474. DateTime objects do not have a numeric value, using C<==> or C<< <=>
  3475. >> to compare a DateTime object with a non-DateTime object will result
  3476. in an exception.  To safely sort mixed DateTime and non-DateTime
  3477. objects, use C<sort { $a cmp $b } @dates>.
  3478.  
  3479. The module also overloads stringification using the object's
  3480. formatter, defaulting to C<iso8601()> method.  See L<Formatters And
  3481. Stringification> for details.
  3482.  
  3483. =head2 Formatters And Stringification
  3484.  
  3485. You can optionally specify a "formatter", which is usually a
  3486. DateTime::Format::* object/class, to control the stringification of
  3487. the DateTime object.
  3488.  
  3489. Any of the constructor methods can accept a formatter argument:
  3490.  
  3491.   my $formatter = DateTime::Format::Strptime->new(...);
  3492.   my $dt = DateTime->new(year => 2004, formatter => $formatter);
  3493.  
  3494. Or, you can set it afterwards:
  3495.  
  3496.   $dt->set_formatter($formatter);
  3497.   $formatter = $dt->formatter();
  3498.  
  3499. Once you set the formatter, the overloaded stringification method will
  3500. use the formatter. If unspecified, the C<iso8601()> method is used.
  3501.  
  3502. A formatter can be handy when you know that in your application you
  3503. want to stringify your DateTime objects into a special format all the
  3504. time, for example to a different language.
  3505.  
  3506. If you provide a formatter class name or object, it must implement a
  3507. C<format_datetime> method. This method will be called with just the
  3508. DateTime object as its argument.
  3509.  
  3510. =head2 strftime Patterns
  3511.  
  3512. The following patterns are allowed in the format string given to the
  3513. C<< $dt->strftime() >> method:
  3514.  
  3515. =over 4
  3516.  
  3517. =item * %a
  3518.  
  3519. The abbreviated weekday name.
  3520.  
  3521. =item * %A
  3522.  
  3523. The full weekday name.
  3524.  
  3525. =item * %b
  3526.  
  3527. The abbreviated month name.
  3528.  
  3529. =item * %B
  3530.  
  3531. The full month name.
  3532.  
  3533. =item * %c
  3534.  
  3535. The default datetime format for the object's locale.
  3536.  
  3537. =item * %C
  3538.  
  3539. The century number (year/100) as a 2-digit integer.
  3540.  
  3541. =item * %d
  3542.  
  3543. The day of the month as a decimal number (range 01 to 31).
  3544.  
  3545. =item * %D
  3546.  
  3547. Equivalent to %m/%d/%y.  This is not a good standard format if you
  3548. want folks from both the United States and the rest of the world to
  3549. understand the date!
  3550.  
  3551. =item * %e
  3552.  
  3553. Like %d, the day of the month as a decimal number, but a leading zero
  3554. is replaced by a space.
  3555.  
  3556. =item * %F
  3557.  
  3558. Equivalent to %Y-%m-%d (the ISO 8601 date format)
  3559.  
  3560. =item * %G
  3561.  
  3562. The ISO 8601 year with century as a decimal number.  The 4-digit year
  3563. corresponding to the ISO week number (see %V).  This has the same
  3564. format and value as %Y, except that if the ISO week number belongs to
  3565. the previous or next year, that year is used instead. (TZ)
  3566.  
  3567. =item * %g
  3568.  
  3569. Like %G, but without century, i.e., with a 2-digit year (00-99).
  3570.  
  3571. =item * %h
  3572.  
  3573. Equivalent to %b.
  3574.  
  3575. =item * %H
  3576.  
  3577. The hour as a decimal number using a 24-hour clock (range 00 to 23).
  3578.  
  3579. =item * %I
  3580.  
  3581. The hour as a decimal number using a 12-hour clock (range 01 to 12).
  3582.  
  3583. =item * %j
  3584.  
  3585. The day of the year as a decimal number (range 001 to 366).
  3586.  
  3587. =item * %k
  3588.  
  3589. The hour (24-hour clock) as a decimal number (range 0 to 23); single
  3590. digits are preceded by a blank. (See also %H.)
  3591.  
  3592. =item * %l
  3593.  
  3594. The hour (12-hour clock) as a decimal number (range 1 to 12); single
  3595. digits are preceded by a blank. (See also %I.)
  3596.  
  3597. =item * %m
  3598.  
  3599. The month as a decimal number (range 01 to 12).
  3600.  
  3601. =item * %M
  3602.  
  3603. The minute as a decimal number (range 00 to 59).
  3604.  
  3605. =item * %n
  3606.  
  3607. A newline character.
  3608.  
  3609. =item * %N
  3610.  
  3611. The fractional seconds digits. Default is 9 digits (nanoseconds).
  3612.  
  3613.   %3N   milliseconds (3 digits)
  3614.   %6N   microseconds (6 digits)
  3615.   %9N   nanoseconds  (9 digits)
  3616.  
  3617. =item * %p
  3618.  
  3619. Either `AM' or `PM' according to the given time value, or the
  3620. corresponding strings for the current locale.  Noon is treated as `pm'
  3621. and midnight as `am'.
  3622.  
  3623. =item * %P
  3624.  
  3625. Like %p but in lowercase: `am' or `pm' or a corresponding string for
  3626. the current locale.
  3627.  
  3628. =item * %r
  3629.  
  3630. The time in a.m.  or p.m. notation.  In the POSIX locale this is
  3631. equivalent to `%I:%M:%S %p'.
  3632.  
  3633. =item * %R
  3634.  
  3635. The time in 24-hour notation (%H:%M). (SU) For a version including the
  3636. seconds, see %T below.
  3637.  
  3638. =item * %s
  3639.  
  3640. The number of seconds since the epoch.
  3641.  
  3642. =item * %S
  3643.  
  3644. The second as a decimal number (range 00 to 61).
  3645.  
  3646. =item * %t
  3647.  
  3648. A tab character.
  3649.  
  3650. =item * %T
  3651.  
  3652. The time in 24-hour notation (%H:%M:%S).
  3653.  
  3654. =item * %u
  3655.  
  3656. The day of the week as a decimal, range 1 to 7, Monday being 1.  See
  3657. also %w.
  3658.  
  3659. =item * %U
  3660.  
  3661. The week number of the current year as a decimal number, range 00 to
  3662. 53, starting with the first Sunday as the first day of week 01. See
  3663. also %V and %W.
  3664.  
  3665. =item * %V
  3666.  
  3667. The ISO 8601:1988 week number of the current year as a decimal number,
  3668. range 01 to 53, where week 1 is the first week that has at least 4
  3669. days in the current year, and with Monday as the first day of the
  3670. week. See also %U and %W.
  3671.  
  3672. =item * %w
  3673.  
  3674. The day of the week as a decimal, range 0 to 6, Sunday being 0.  See
  3675. also %u.
  3676.  
  3677. =item * %W
  3678.  
  3679. The week number of the current year as a decimal number, range 00 to
  3680. 53, starting with the first Monday as the first day of week 01.
  3681.  
  3682. =item * %x
  3683.  
  3684. The default date format for the object's locale.
  3685.  
  3686. =item * %X
  3687.  
  3688. The default time format for the object's locale.
  3689.  
  3690. =item * %y
  3691.  
  3692. The year as a decimal number without a century (range 00 to 99).
  3693.  
  3694. =item * %Y
  3695.  
  3696. The year as a decimal number including the century.
  3697.  
  3698. =item * %z
  3699.  
  3700. The time-zone as hour offset from UTC.  Required to emit
  3701. RFC822-conformant dates (using "%a, %d %b %Y %H:%M:%S %z").
  3702.  
  3703. =item * %Z
  3704.  
  3705. The time zone or name or abbreviation.
  3706.  
  3707. =item * %%
  3708.  
  3709. A literal `%' character.
  3710.  
  3711. =item * %{method}
  3712.  
  3713. Any method name may be specified using the format C<%{method}> name
  3714. where "method" is a valid C<DateTime.pm> object method.
  3715.  
  3716. =back
  3717.  
  3718. =head2 CLDR Patterns
  3719.  
  3720. The CLDR pattern language is both more powerful and more complex than
  3721. strftime. Unlike strftime patterns, you often have to explicitly
  3722. escape text that you do not want formatted, as the patterns are simply
  3723. letters without any prefix.
  3724.  
  3725. For example, "yyyy-MM-dd" is a valid CLDR pattern. If you want to
  3726. include any lower or upper case ASCII characters as-is, you can
  3727. surround them with single quotes ('). If you want to include a single
  3728. quote, you must escape it as two single quotes ('').
  3729.  
  3730.   'Today is ' EEEE
  3731.   'It is now' h 'o''clock' a
  3732.  
  3733. Spaces and any non-letter text will always be passed through as-is.
  3734.  
  3735. Many CLDR patterns which produce numbers will pad the number with
  3736. leading zeroes depending on the length of the format specifier. For
  3737. example, "h" represents the current hour from 1-12. If you specify
  3738. "hh" then the 1-9 will have a leading zero prepended.
  3739.  
  3740. However, CLDR often uses five of a letter to represent the narrow form
  3741. of a pattern. This inconsistency is necessary for backwards
  3742. compatibility.
  3743.  
  3744. CLDR often distinguishes between the "format" and "stand-alone" forms
  3745. of a pattern. The format pattern is used when the thing in question is
  3746. being placed into a larger string. The stand-alone form is used when
  3747. displaying that item by itself, for example in a calendar.
  3748.  
  3749. It also often provides three sizes for each item, wide (the full
  3750. name), abbreviated, and narrow. The narrow form is often just a single
  3751. character, for example "T" for "Tuesday", and may not be unique.
  3752.  
  3753. CLDR provides a fairly complex system for localizing time zones that
  3754. we ignore entirely. The time zone patterns just use the information
  3755. provided by C<DateTime::TimeZone>, and I<do not follow the CLDR spec>.
  3756.  
  3757. The output of a CLDR pattern is always localized, when applicable.
  3758.  
  3759. CLDR provides the following patterns:
  3760.  
  3761. =over 4
  3762.  
  3763. =item * G{1,3}
  3764.  
  3765. The abbreviated era (BC, AD).
  3766.  
  3767. =item * GGGG
  3768.  
  3769. The wide era (Before Christ, Anno Domini).
  3770.  
  3771. =item * GGGGG
  3772.  
  3773. The narrow era, if it exists (and it mostly doesn't).
  3774.  
  3775. =item * y and y{3,}
  3776.  
  3777. The year, zero-prefixed as needed. Negative years will start with a "-",
  3778. and this will be included in the length calculation.
  3779.  
  3780. In other, words the "yyyyy" pattern will format year -1234 as "-1234", not
  3781. "-01234".
  3782.  
  3783. =item * yy
  3784.  
  3785. This is a special case. It always produces a two-digit year, so "1976" becomes
  3786. "76". Negative years will start with a "-", making them one character longer.
  3787.  
  3788. =item * Y{1,}
  3789.  
  3790. The week of the year, from C<< $dt->week_year() >>.
  3791.  
  3792. =item * u{1,}
  3793.  
  3794. Same as "y" except that "uu" is not a special case.
  3795.  
  3796. =item * Q{1,2}
  3797.  
  3798. The quarter as a number (1..4).
  3799.  
  3800. =item * QQQ
  3801.  
  3802. The abbreviated format form for the quarter.
  3803.  
  3804. =item * QQQQ
  3805.  
  3806. The wide format form for the quarter.
  3807.  
  3808. =item * q{1,2}
  3809.  
  3810. The quarter as a number (1..4).
  3811.  
  3812. =item * qqq
  3813.  
  3814. The abbreviated stand-alone form for the quarter.
  3815.  
  3816. =item * qqqq
  3817.  
  3818. The wide stand-alone form for the quarter.
  3819.  
  3820. =item * M{1,2]
  3821.  
  3822. The numerical month.
  3823.  
  3824. =item * MMM
  3825.  
  3826. The abbreviated format form for the month.
  3827.  
  3828. =item * MMMM
  3829.  
  3830. The wide format form for the month.
  3831.  
  3832. =item * MMMMM
  3833.  
  3834. The narrow format form for the month.
  3835.  
  3836. =item * L{1,2]
  3837.  
  3838. The numerical month.
  3839.  
  3840. =item * LLL
  3841.  
  3842. The abbreviated stand-alone form for the month.
  3843.  
  3844. =item * LLLL
  3845.  
  3846. The wide stand-alone form for the month.
  3847.  
  3848. =item * LLLLL
  3849.  
  3850. The narrow stand-alone form for the month.
  3851.  
  3852. =item * w{1,2}
  3853.  
  3854. The week of the year, from C<< $dt->week_number() >>.
  3855.  
  3856. =item * W
  3857.  
  3858. The week of the month, from C<< $dt->week_of_month() >>.
  3859.  
  3860. =item * d{1,2}
  3861.  
  3862. The numeric day of of the month.
  3863.  
  3864. =item * D{1,3}
  3865.  
  3866. The numeric day of of the year.
  3867.  
  3868. =item * F
  3869.  
  3870. The day of the week in the month, from C<< $dt->weekday_of_month() >>.
  3871.  
  3872. =item * g{1,}
  3873.  
  3874. The modified Julian day, from C<< $dt->mjd() >>.
  3875.  
  3876. =item * E{1,3} and eee
  3877.  
  3878. The abbreviated format form for the day of the week.
  3879.  
  3880. =item * EEEE and eeee
  3881.  
  3882. The wide format form for the day of the week.
  3883.  
  3884. =item * EEEEE and eeeee
  3885.  
  3886. The narrow format form for the day of the week.
  3887.  
  3888. =item * e{1,2}
  3889.  
  3890. The I<local> numeric day of the week, from 1 to 7. This number depends
  3891. on what day is considered the first day of the week, which varies by
  3892. locale. For example, in the US, Sunday is the first day of the week,
  3893. so this returns 2 for Monday.
  3894.  
  3895. =item * c
  3896.  
  3897. The numeric day of the week from 1 to 7, treating Monday as the first
  3898. of the week, regardless of locale.
  3899.  
  3900. =item * ccc
  3901.  
  3902. The abbreviated stand-alone form for the day of the week.
  3903.  
  3904. =item * cccc
  3905.  
  3906. The wide stand-alone form for the day of the week.
  3907.  
  3908. =item * ccccc
  3909.  
  3910. The narrow format form for the day of the week.
  3911.  
  3912. =item * a
  3913.  
  3914. The localized form of AM or PM for the time.
  3915.  
  3916. =item * h{1,2}
  3917.  
  3918. The hour from 1-12.
  3919.  
  3920. =item * H{1,2}
  3921.  
  3922. The hour from 0-23.
  3923.  
  3924. =item * K{1,2}
  3925.  
  3926. The hour from 0-11.
  3927.  
  3928. =item * k{1,2}
  3929.  
  3930. The hour from 1-24.
  3931.  
  3932. =item * j{1,2}
  3933.  
  3934. The hour, in 12 or 24 hour form, based on the preferred form for the
  3935. locale. In other words, this is equivalent to either "h{1,2}" or
  3936. "H{1,2}".
  3937.  
  3938. =item * m{1,2}
  3939.  
  3940. The minute.
  3941.  
  3942. =item * s{1,2}
  3943.  
  3944. The second.
  3945.  
  3946. =item * S{1,}
  3947.  
  3948. The fractional portion of the seconds, rounded based on the length of
  3949. the specifier. This returned I<without> a leading decimal point, but
  3950. may have leading or trailing zeroes.
  3951.  
  3952. =item * A{1,}
  3953.  
  3954. The millisecond of the day, based on the current time. In other words,
  3955. if it is 12:00:00.00, this returns 43200000.
  3956.  
  3957. =item * z{1,3}
  3958.  
  3959. The time zone short name.
  3960.  
  3961. =item * zzzz
  3962.  
  3963. The time zone long name.
  3964.  
  3965. =item * Z{1,3}
  3966.  
  3967. The time zone short name and the offset as one string, so something
  3968. like "CDT-0500".
  3969.  
  3970. =item * ZZZZ
  3971.  
  3972. The time zone long name.
  3973.  
  3974. =item * v{1,3}
  3975.  
  3976. The time zone short name.
  3977.  
  3978. =item * vvvv
  3979.  
  3980. The time zone long name.
  3981.  
  3982. =item * V{1,3}
  3983.  
  3984. The time zone short name.
  3985.  
  3986. =item * VVVV
  3987.  
  3988. The time zone long name.
  3989.  
  3990. =back
  3991.  
  3992. =head1 DateTime.pm and Storable
  3993.  
  3994. DateTime implements Storable hooks in order to reduce the size of a
  3995. serialized DateTime object.
  3996.  
  3997. =head1 KNOWN BUGS
  3998.  
  3999. The tests in F<20infinite.t> seem to fail on some machines,
  4000. particularly on Win32.  This appears to be related to Perl's internal
  4001. handling of IEEE infinity and NaN, and seems to be highly
  4002. platform/compiler/phase of moon dependent.
  4003.  
  4004. If you don't plan to use infinite datetimes you can probably ignore
  4005. this.  This will be fixed (somehow) in future versions.
  4006.  
  4007. =head1 SUPPORT
  4008.  
  4009. Support for this module is provided via the datetime@perl.org email
  4010. list. See http://datetime.perl.org/?MailingList for details.
  4011.  
  4012. Please submit bugs to the CPAN RT system at
  4013. http://rt.cpan.org/NoAuth/ReportBug.html?Queue=datetime or via email
  4014. at bug-datetime@rt.cpan.org.
  4015.  
  4016. =head1 DONATIONS
  4017.  
  4018. If you'd like to thank me for the work I've done on this module,
  4019. please consider making a "donation" to me via PayPal. I spend a lot of
  4020. free time creating free software, and would appreciate any support
  4021. you'd care to offer.
  4022.  
  4023. Please note that B<I am not suggesting that you must do this> in order
  4024. for me to continue working on this particular software. I will
  4025. continue to do so, inasmuch as I have in the past, for as long as it
  4026. interests me.
  4027.  
  4028. Similarly, a donation made in this way will probably not make me work
  4029. on this software much more, unless I get so many donations that I can
  4030. consider working on free software full time, which seems unlikely at
  4031. best.
  4032.  
  4033. To donate, log into PayPal and send money to autarch@urth.org or use
  4034. the button on this page:
  4035. L<http://www.urth.org/~autarch/fs-donation.html>
  4036.  
  4037. =head1 SEE ALSO
  4038.  
  4039. datetime@perl.org mailing list
  4040.  
  4041. http://datetime.perl.org/
  4042.  
  4043. =head1 AUTHOR
  4044.  
  4045. Dave Rolsky <autarch@urth.org>
  4046.  
  4047. =head1 COPYRIGHT AND LICENSE
  4048.  
  4049. This software is Copyright (c) 2010 by Dave Rolsky.
  4050.  
  4051. This is free software, licensed under:
  4052.  
  4053.   The Artistic License 2.0
  4054.  
  4055. =cut
  4056.  
  4057.  
  4058. __END__
  4059.  
  4060.